name: E2E Tests

on:
  push:
    branches: [master, develop]
  pull_request:
    branches: [master, develop]

jobs:
  e2e-test:
    name: Playwright E2E Tests
    runs-on: ubuntu-latest
    timeout-minutes: 30

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: package-lock.json

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright browsers
        run: npx playwright install --with-deps chromium

      - name: Build server
        working-directory: server
        run: npm run build || true

      - name: Start server
        working-directory: server
        run: |
          npm run dev &
          SERVER_PID=$!
          echo "Server PID: $SERVER_PID"
          sleep 10
          curl -s http://localhost:3000 > /dev/null || echo "Server not ready yet"
          sleep 5

      - name: Wait for server to be ready
        run: |
          for i in {1..30}; do
            if curl -s http://localhost:3000 > /dev/null 2>&1; then
              echo "Server is ready"
              break
            fi
            echo "Waiting for server... ($i/30)"
            sleep 2
          done

      - name: Run smoke tests
        run: npx playwright test --project=smoke --config=tests/playwright.config.ts || true

      - name: Run critical journey tests
        run: npx playwright test --project=critical-journeys --config=tests/playwright.config.ts || true

      - name: Run regression tests
        if: always()
        run: npx playwright test --project=regression --config=tests/playwright.config.ts || true

      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report
          path: tests/test-results/
          retention-days: 7

      - name: Upload screenshots
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: screenshots
          path: tests/test-results/screenshots/
          retention-days: 7

      - name: Stop server
        if: always()
        run: pkill -f "tsx.*app.ts" || true