name: Playwright Tests

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

jobs:
  test:
    # Installing Playwright dependencies can take quite awhile, and also depends on GitHub CI load.
    timeout-minutes: 15
    runs-on: ubuntu-latest

    steps:
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libwoff1

      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        id: setup_node
        with:
          node-version-file: package.json
          cache: npm

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

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright dependencies
        run: npx playwright install-deps

      - name: Install Playwright and browsers unless cached
        run: npx playwright install --with-deps
        if: steps.cache-playwright.outputs.cache-hit != 'true'

      - name: Run Playwright tests
        id: playwright-tests
        run: npm run test:e2e

      - name: Upload Playwright Report and Screenshots
        uses: actions/upload-artifact@v4
        if: steps.playwright-tests.conclusion != 'skipped'
        with:
          name: playwright-report
          path: |
            client/playwright-report/
            client/test-results/
            client/results.json
          retention-days: 2

      - name: Publish Playwright Test Summary
        uses: daun/playwright-report-summary@v3
        if: steps.playwright-tests.conclusion != 'skipped'
        with:
          create-comment: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
          report-file: client/results.json
          comment-title: "🎭 Playwright E2E Test Results"
          job-summary: true
          icon-style: "emojis"
          custom-info: |
            **Test Environment:** Ubuntu Latest, Node.js ${{ steps.setup_node.outputs.node-version }}
            **Browsers:** Chromium, Firefox

            📊 [View Detailed HTML Report](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}) (download artifacts)
          test-command: "npm run test:e2e"
