name: TaxBaik Browser E2E

on:
  workflow_run:
    workflows: ["TaxBaik CI/CD"]
    types:
      - completed

jobs:
  browser-e2e:
    runs-on: ubuntu-latest
    if: github.event.workflow_run.conclusion == 'success'

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm

      - name: Cache Playwright browsers
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/ms-playwright
          key: ${{ runner.os }}-playwright-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-playwright-

      - name: Install Playwright dependencies
        run: |
          set -e
          npm ci
          npx playwright install chromium --with-deps

      - name: Validate locked DB connection string
        run: |
          set -e
          python3 scripts/validate_locked_db_connection.py

      - name: Wait for deployment
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          EXPECTED_VERSION: ${{ github.event.workflow_run.head_sha }}
        run: |
          set -e
          # Extract short commit hash (first 7 characters)
          SHORT_VERSION=$(echo "$EXPECTED_VERSION" | cut -c1-7)
          echo "Expected short version: $SHORT_VERSION"
          for i in $(seq 1 20); do
            # Suppress stderr and allow failures to handle transition/down periods cleanly
            VERSION_BODY="$(curl -fsS "https://www.taxbaik.com/taxbaik/version.json" 2>/dev/null || true)"
            BLOG_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "https://www.taxbaik.com/taxbaik/blog/accountant-mistakes-5" || true)"
            LOGIN_STATUS="$(curl -s -o /dev/null -w '%{http_code}' "https://www.taxbaik.com/taxbaik/admin/login" || true)"
            if echo "$VERSION_BODY" | grep -q "\"version\": \"${SHORT_VERSION}\"" && [ "$BLOG_STATUS" = "200" ] && [ "$LOGIN_STATUS" = "200" ]; then
              echo "✓ Deployment ready for ${SHORT_VERSION} (attempt $i/20)"
              ROOT_URL="https://www.taxbaik.com/" \
              ADMIN_URL="https://www.taxbaik.com/taxbaik/admin/login" \
              PUBLIC_MARKER="백원숙 세무회계" \
              PUBLIC_FORBIDDEN="관리자" \
              ADMIN_MARKER="관리자 로그인" \
              MAX_RETRIES=1 \
              bash ./scripts/taxbaik-smoke.sh
              exit 0
            fi
            if [ $i -lt 20 ]; then
              echo "  Attempt $i/20: waiting for deployment... (blog=${BLOG_STATUS:-?}, login=${LOGIN_STATUS:-?}, version=${VERSION_BODY:0:30}...)"
              sleep 3
            fi
          done
          echo "✗ TIMEOUT: Deployment failed to publish ${SHORT_VERSION} within 60 seconds" >&2
          exit 1

      - name: Browser verifications in parallel
        env:
          # Green-Blue 배포 지원: Nginx를 통해 active 포트로 라우팅
          E2E_BASE_URL: https://www.taxbaik.com/taxbaik
          # E2E 테스트는 운영에서 검증된 admin 계정 사용
          E2E_ADMIN_USERNAME: admin
          E2E_ADMIN_PASSWORD: ${{ secrets.E2E_ADMIN_PASSWORD }}
          EVIDENCE_ROOT: evidence
        run: |
          set -e
          pids=()
          names=()

          run_job() {
            local name="$1"
            shift
            (
              echo "=== START ${name} ==="
              "$@"
              echo "=== DONE ${name} ==="
            ) &
            pids+=($!)
            names+=("$name")
          }

          run_job "browser-smoke" bash -lc 'npm run test:e2e:public-smoke && npm run test:e2e:admin-smoke'
          run_job "browser-e2e" bash -lc 'npm run test:e2e:ci'
          run_job "api-smoke" bash -lc '
            set -e
            TOKEN="$(curl -s -X POST "https://www.taxbaik.com/taxbaik/api/auth/login" -H "Content-Type: application/json" -d "{\"username\":\"${E2E_ADMIN_USERNAME}\",\"password\":\"${E2E_ADMIN_PASSWORD}\"}" | python3 -c '\''import sys, json; print(json.load(sys.stdin)["accessToken"])'\'')"
            test -n "$TOKEN"
            curl -fsS -H "Authorization: Bearer $TOKEN" "https://www.taxbaik.com/taxbaik/api/blog/admin?page=1&pageSize=1" >/dev/null
            curl -fsS -H "Authorization: Bearer $TOKEN" "https://www.taxbaik.com/taxbaik/api/faq" >/dev/null
            curl -fsS -H "Authorization: Bearer $TOKEN" "https://www.taxbaik.com/taxbaik/api/announcement" >/dev/null
            curl -fsS -H "Authorization: Bearer $TOKEN" "https://www.taxbaik.com/taxbaik/api/inquiry?page=1&pageSize=1" >/dev/null
            curl -fsS "https://www.taxbaik.com/taxbaik/favicon.svg" >/dev/null
            curl -fsS "https://www.taxbaik.com/taxbaik/favicon.ico" >/dev/null
            curl -fsS "https://www.taxbaik.com/taxbaik/robots.txt" >/dev/null
          '

          failures=0
          for idx in "${!pids[@]}"; do
            pid="${pids[$idx]}"
            name="${names[$idx]}"
            if wait "$pid"; then
              echo "✓ ${name} passed"
            else
              echo "✗ ${name} failed" >&2
              failures=1
            fi
          done

          exit "$failures"

      - name: Upload Playwright artifacts
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-artifacts
          path: |
            playwright-report/
            test-results/
            evidence/
          if-no-files-found: ignore

      - name: Verify evidence manifest
        if: always()
        run: |
          set -e
          python3 scripts/verify_evidence_manifest.py evidence

      - name: Browser E2E summary
        if: always()
        run: |
          echo "Executed tests:"
          echo "- admin-login"
          echo "- admin-smoke"
          echo "- public-smoke"
          echo "- blog-seo"
          echo "- contact-submit"
          echo "- inquiry-detail"
          echo "- admin-password-change"
          if [ -f evidence/manifest.jsonl ]; then
            echo "Evidence manifest entries:"
            wc -l evidence/manifest.jsonl
          else
            echo "Evidence manifest entries: 0"
          fi
