stages:
  - deploy
deploy:
  stage: deploy
  image: node:22-slim
  before_script:
    - |
      # Cloudflare API helper based on Node 22 built-in fetch.
      # Avoids depending on curl / apt-get, which is unavailable on slim images.
      cat > /tmp/cf-api.js <<'CF_API_EOF'
      const [method, path, body] = process.argv.slice(2);
      const headers = { 'Content-Type': 'application/json' };
      if (process.env.CLOUDFLARE_AUTH_KEY && process.env.CLOUDFLARE_AUTH_EMAIL) {
        headers['X-Auth-Key'] = process.env.CLOUDFLARE_AUTH_KEY;
        headers['X-Auth-Email'] = process.env.CLOUDFLARE_AUTH_EMAIL;
      } else {
        headers.Authorization = `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`;
      }
      fetch(`https://api.cloudflare.com/client/v4${path}`, { method, headers, body })
        .then((res) => res.text())
        .then((text) => console.log(text))
        .catch((err) => console.log(JSON.stringify({ success: false, error: String(err) })));
      CF_API_EOF
    - |
      # For shell executor: Setup nvm and ensure Node.js 22+ is available
      # (Docker executor will use image: node:22-slim, so Node.js is already available)
      if ! command -v node &> /dev/null; then
        export NVM_DIR="$HOME/.nvm"
        if [ -s "$NVM_DIR/nvm.sh" ]; then
          source "$NVM_DIR/nvm.sh"
        else
          echo "Installing nvm..."
          curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
          export NVM_DIR="$HOME/.nvm"
          [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"
        fi
        # Install Node.js 22
        echo "Installing Node.js 22..."
        nvm install 22
        nvm use 22
      else
        # Node.js is available, check version and upgrade to 22 if needed
        export NVM_DIR="$HOME/.nvm"
        if [ -s "$NVM_DIR/nvm.sh" ]; then
          source "$NVM_DIR/nvm.sh"
          NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
          if [ "$NODE_VERSION" -lt 22 ]; then
            echo "Node.js version is less than 22. Installing Node.js 22..."
            nvm install 22
            nvm use 22
          fi
        fi
      fi
      # Verify Node.js 20+ and npm are available
      node --version || (echo "ERROR: Node.js not found. Please install Node.js on the GitLab runner." && exit 1)
      NODE_MAJOR=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
      if [ "$NODE_MAJOR" -lt 20 ]; then
        echo "ERROR: Node.js version must be at least 20.0.0. Current version: $(node --version)" && exit 1
      fi
      npm --version || (echo "ERROR: npm not found. Please install npm on the GitLab runner." && exit 1)
      # Install wrangler globally
      npm install -g wrangler@4.116.0
  script:
    - |
      echo "=== Checking Cloudflare CI/CD Variables ==="
      if [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then
        echo "ERROR: CLOUDFLARE_ACCOUNT_ID is not set!"
        exit 1
      else
        ACCOUNT_ID_LEN=$(echo -n "$CLOUDFLARE_ACCOUNT_ID" | wc -c)
        echo "CLOUDFLARE_ACCOUNT_ID: [SET] (length: $ACCOUNT_ID_LEN)"
      fi
      if [ -z "$CLOUDFLARE_ZONE_ID" ]; then
        echo "WARNING: CLOUDFLARE_ZONE_ID is not set — zone cache purge will be skipped (Pages-only deploy)"
      else
        echo "CLOUDFLARE_ZONE_ID: $CLOUDFLARE_ZONE_ID"
      fi
      # Auth precedence for Cloudflare API: Global API Key (X-Auth-Key + X-Auth-Email) → fallback to Bearer (CLOUDFLARE_API_TOKEN).
      if [ -n "$CLOUDFLARE_AUTH_KEY" ] && [ -n "$CLOUDFLARE_AUTH_EMAIL" ]; then
        AUTH_KEY_LEN=$(echo -n "$CLOUDFLARE_AUTH_KEY" | wc -c)
        echo "CLOUDFLARE_AUTH_KEY: [SET] (length: $AUTH_KEY_LEN)"
        echo "CLOUDFLARE_AUTH_EMAIL: $CLOUDFLARE_AUTH_EMAIL"
      elif [ -n "$CLOUDFLARE_API_TOKEN" ]; then
        TOKEN_LEN=$(echo -n "$CLOUDFLARE_API_TOKEN" | wc -c)
        echo "CLOUDFLARE_API_TOKEN: [SET] (length: $TOKEN_LEN) — Global API Key not provided, falling back to Bearer"
      else
        echo "ERROR: Set CLOUDFLARE_AUTH_KEY and CLOUDFLARE_AUTH_EMAIL (preferred), or CLOUDFLARE_API_TOKEN."
        exit 1
      fi
      echo "==========================================="
    - |
      echo "=== Setting SSL/TLS encryption mode to Full ==="
      if [ -z "$CLOUDFLARE_ZONE_ID" ]; then
        echo "Skipping SSL mode (no CLOUDFLARE_ZONE_ID — e.g. Pages-only on *.pages.dev). Set CLOUDFLARE_ZONE_ID for your custom-domain zone."
      else
        RESPONSE=$(node /tmp/cf-api.js PATCH "/zones/$CLOUDFLARE_ZONE_ID/settings/ssl" '{"value": "full"}')
        if echo "$RESPONSE" | grep -q '"success":true'; then
          echo "Successfully set SSL/TLS encryption mode to Full."
        else
          echo "WARNING: Failed to set SSL mode; continuing deploy. API Response: $RESPONSE"
        fi
      fi
      echo "================================="
    - wrangler pages deploy ./ --project-name=labradorsilver-com-108861 --branch=master
    - |
      echo "=== Purging Cloudflare cache ==="
      if [ -z "$CLOUDFLARE_ZONE_ID" ]; then
        echo "Skipping zone purge (no CLOUDFLARE_ZONE_ID)"
      else
        node /tmp/cf-api.js POST "/zones/$CLOUDFLARE_ZONE_ID/purge_cache" '{"purge_everything":true}'
      fi
      echo "================================="
  only:
    - master
