name: Deploy Preview

on:
  push:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: deploy-preview-${{ github.ref }}
  cancel-in-progress: false

permissions:
  contents: read

env:
  BUILD_NO_LOCK: '1'

jobs:
  deploy-preview:
    name: Build + deploy preview
    runs-on: [self-hosted, linux, x64, multideal-gate]
    timeout-minutes: 60
    outputs:
      preview_url: ${{ steps.deploy.outputs.preview_url }}
    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      NODE_OPTIONS: --max-old-space-size=6144
      BUILD_CPU_RESERVE: '2'
      BUILD_SCHED_IDLE: '0'
    steps:
      - uses: actions/checkout@v7
      - uses: ./.github/actions/setup
        with:
          github-packages-token: ${{ secrets.GH_PKG_READ_TOKEN }}
      - name: Build (preview)
        env:
          PUBLIC_TURNSTILE_SITE_KEY: ${{ vars.TURNSTILE_SITE_KEY }}
        run: |
          rm -rf apps/web/dist
          bash apps/web/scripts/cpu-limit.sh pnpm --filter @multideal/web build
          pnpm --filter @multideal/web exec node scripts/verify-deploy-dist.mjs --write-stamp
      - name: Verify built Worker config
        run: node scripts/verify-worker-config.mjs
      - name: Verify deploy dist budget
        run: pnpm --filter @multideal/web exec node scripts/verify-deploy-dist.mjs
      - name: Deploy to Cloudflare Workers (preview)
        id: deploy
        run: |
          DEPLOY_LOG=$(pnpm --filter @multideal/web deploy:preview 2>&1)
          echo "$DEPLOY_LOG"
          DEPLOY_URL=$(printf '%s\n' "$DEPLOY_LOG" | grep -oE 'https://[^ ]+\.workers\.dev' | tail -1)
          echo "preview_url=${DEPLOY_URL}" >> "$GITHUB_OUTPUT"
      - name: Verify SchedulerDO alarm
        env:
          CRON_SECRET: ${{ secrets.CRON_SECRET }}
          DEPLOY_URL: https://dev.multi.deal
        run: node scripts/verify-scheduler-armed.mjs
      - name: Notify Telegram - success
        if: success()
        env:
          TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
          TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
          PREVIEW_URL: ${{ steps.deploy.outputs.preview_url }}
          SERVER_URL: ${{ github.server_url }}
          REPOSITORY: ${{ github.repository }}
          RUN_ID: ${{ github.run_id }}
          COMMIT_SHA: ${{ github.sha }}
        run: |
          if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then exit 0; fi
          LINK="${PREVIEW_URL:-${SERVER_URL}/${REPOSITORY}/actions/runs/${RUN_ID}}"
          TG_MESSAGE=$(printf "🚀 Preview deployed (main@%s)\n%s" "${COMMIT_SHA:0:8}" "$LINK")
          export TG_MESSAGE
          curl -s -X POST \
            "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
            --data-urlencode "text=${TG_MESSAGE}" \
            -d "chat_id=${TELEGRAM_CHAT_ID}" \
            -d "parse_mode=HTML" \
            -d "disable_web_page_preview=true"
      - name: Notify Telegram - failure
        if: failure()
        env:
          TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
          TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
          SERVER_URL: ${{ github.server_url }}
          REPOSITORY: ${{ github.repository }}
          RUN_ID: ${{ github.run_id }}
        run: |
          if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then exit 0; fi
          RUN_URL="${SERVER_URL}/${REPOSITORY}/actions/runs/${RUN_ID}"
          TG_MESSAGE=$(printf "⚠️ Preview deploy failed (main)\n%s" "$RUN_URL")
          export TG_MESSAGE
          curl -s -X POST \
            "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
            --data-urlencode "text=${TG_MESSAGE}" \
            -d "chat_id=${TELEGRAM_CHAT_ID}" \
            -d "parse_mode=HTML" \
            -d "disable_web_page_preview=true"

  smoke:
    name: Playwright smoke
    needs: [deploy-preview]
    runs-on: [self-hosted, linux, x64, multideal-gate]
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - uses: ./.github/actions/setup
        with:
          github-packages-token: ${{ secrets.GH_PKG_READ_TOKEN }}
      - working-directory: apps/web
        run: pnpm exec playwright install chromium
      - name: Verify home, deal detail, login, and cart on the deployed build
        working-directory: apps/web
        env:
          # The versioned workers.dev URL pins the probe to the build this run deployed.
          SMOKE_BASE_URL: ${{ needs.deploy-preview.outputs.preview_url }}
        run: |
          node --input-type=module <<'EOF'
          import { chromium } from '@playwright/test';

          const baseUrl = (process.env.SMOKE_BASE_URL || '').trim();
          if (!baseUrl) throw new Error('deploy-preview did not emit preview_url; refusing to probe an unpinned host');
          const browser = await chromium.launch({ headless: true });
          try {
            const page = await browser.newPage();
            const requireOk = async (path) => {
              const response = await page.goto(`${baseUrl}${path}`, { waitUntil: 'domcontentloaded' });
              if (!response || !response.ok()) throw new Error(`${path} returned ${response?.status() ?? 'no response'}`);
            };

            await requireOk('/');
            await requireOk('/login');
            await requireOk('/cart');
            await requireOk('/deals');
            const href = await page.locator('a[href^="/deals/"]').first().getAttribute('href');
            if (!href) throw new Error('No deal-detail link was found on /deals');
            await requireOk(href);
          } finally {
            await browser.close();
          }
          EOF
