name: E2E Tests
on:
  workflow_call:
  workflow_dispatch:
jobs:
  build:
    name: Run E2E Tests
    runs-on: ubuntu-latest
    timeout-minutes: 60
    services:
      postgres:
        image: postgres:latest
        env:
          POSTGRES_DB: postgres
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
        options: >-
          --health-cmd="pg_isready -U testuser"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=5
    steps:
      - uses: actions/checkout@v3
      - uses: ./.github/actions/dangerous-git-checkout

      - name: Build & Cache Web Binaries
        uses: ./.github/actions/cache-build-web
        with:
          e2e_testing_mode: "1"

      - name: Check if pnpm is installed
        id: pnpm-check
        run: |
          if pnpm --version; then
            echo "pnpm is installed."
            echo "PNPM_INSTALLED=true" >> $GITHUB_ENV
          else
            echo "pnpm is not installed."
            echo "PNPM_INSTALLED=false" >> $GITHUB_ENV
          fi

      - name: Install pnpm
        if: env.PNPM_INSTALLED == 'false'
        uses: pnpm/action-setup@v4

      - name: Install dependencies
        if: env.PNPM_INSTALLED == 'false'
        run: pnpm install

      - name: Apply Prisma Migrations
        run: |
          pnpm prisma migrate deploy

      - name: Run App
        run: |
          NODE_ENV=test pnpm start --filter=@formbricks/web &
          sleep 10  # Optional: gives some buffer for the app to start
          for attempt in {1..10}; do
            if [ $(curl -o /dev/null -s -w "%{http_code}" http://localhost:3000/health) -eq 200 ]; then
              echo "Application is ready."
              break
            fi
            if [ $attempt -eq 10 ]; then
              echo "Application failed to start in time."
              exit 1
            fi
            echo "Still waiting for the application to be ready..."
            sleep 10
          done

      - name: Cache Playwright
        uses: actions/cache@v3
        id: playwright-cache
        with:
          path: ~/.cache/ms-playwright
          key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}

      - name: Install Playwright
        if: steps.playwright-cache.outputs.cache-hit != 'true'
        run: pnpm exec playwright install --with-deps

      - name: Run E2E Tests
        run: |
          pnpm test:e2e

      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 30
