name: Tests

on:
  push:
    branches: [dev, main]
  pull_request:
    branches: [dev, main]

jobs:
  unit-tests:
    name: Unit & Integration Tests
    runs-on: ubuntu-latest

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

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

      - name: Install dependencies
        run: npm ci

      - name: Run TypeScript check
        run: npm run types

      - name: Run unit tests with coverage
        run: npm run test:coverage

      - name: Run worker tests
        run: npm run test:worker

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          files: ./coverage/lcov.info
          fail_ci_if_error: false
          verbose: true

  e2e-tests:
    name: 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'

      - name: Install dependencies
        run: npm ci

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

      - name: Run E2E tests
        run: npm run test:e2e
        env:
          CI: true

      - name: Upload Playwright report
        uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 7

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

  build-check:
    name: Build Check
    runs-on: ubuntu-latest

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

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

      - name: Install dependencies
        run: npm ci

      - name: Build project
        run: npm run build
        env:
          NODE_OPTIONS: '--max-old-space-size=8192'

  # Gate job that requires all tests to pass before merge
  merge-ready:
    name: Merge Ready
    needs: [unit-tests, e2e-tests, build-check]
    runs-on: ubuntu-latest
    if: always()

    steps:
      - name: Check all jobs passed
        run: |
          if [[ "${{ needs.unit-tests.result }}" != "success" ]]; then
            echo "Unit tests failed"
            exit 1
          fi
          if [[ "${{ needs.e2e-tests.result }}" != "success" ]]; then
            echo "E2E tests failed"
            exit 1
          fi
          if [[ "${{ needs.build-check.result }}" != "success" ]]; then
            echo "Build check failed"
            exit 1
          fi
          echo "All checks passed - ready to merge!"
