name: E2E Tests

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  e2e:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

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

      - name: Create .env for stack
        run: |
          cat > .env <<'EOF'
          POSTGRES_PASSWORD=ci-postgres-pass
          BRAIN_INTERNAL_SECRET=ci-brain-secret
          ADMIN_USERNAME=admin
          ADMIN_PASSWORD=ci-admin-pass
          WEB_PORT=8081
          LLM_PROVIDER=ollama
          EOF

      - name: Build & start stack
        run: |
          docker compose -f docker-compose.yml -f docker-compose.e2e.yml up -d --build

      - name: Attach runner to compose network
        run: |
          NET=$(docker network ls --format '{{.Name}}' | grep -E '(^|_)loremind(_|$)' | grep -i default | head -1)
          if [ -z "$NET" ]; then
            echo "Compose network not found" >&2
            docker network ls
            exit 1
          fi
          echo "Connecting $(hostname) to network $NET"
          docker network connect "$NET" "$(hostname)"

      - name: Wait for web to be ready
        run: |
          timeout 180 bash -c 'until curl -sf http://web/ > /dev/null; do echo "waiting..."; sleep 3; done'

      - name: Install web deps
        working-directory: web
        run: npm ci

      - name: Work around runner clock skew for apt
        run: |
          sudo tee /etc/apt/apt.conf.d/99no-check-valid-until >/dev/null <<'EOF'
          Acquire::Check-Valid-Until "false";
          Acquire::Check-Date "false";
          EOF

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

      - name: Run Playwright tests
        working-directory: web
        env:
          E2E_BASE_URL: http://web
          CI: 'true'
        run: npm run e2e

      - name: Dump container logs on failure
        if: failure()
        run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color

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

      - name: Stop stack
        if: always()
        run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml down -v
