name: Visual diff

on:
  pull_request:
    branches: [main]
    paths:
      - 'src/app/**'
      - 'src/components/**'
      - 'src/app/globals.css'
      - 'postcss.config.*'

# Skip when PR body contains 'pipeline: ... skip ... visual'
concurrency:
  group: visual-diff-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  gate:
    name: Should run?
    runs-on: ubuntu-latest
    outputs:
      should_run: ${{ steps.check.outputs.should_run }}
    steps:
      - id: check
        run: |
          if echo "${{ github.event.pull_request.body }}" | grep -qE 'pipeline:.*skip.*\bvisual\b'; then
            echo "should_run=false" >> $GITHUB_OUTPUT
            echo "::notice::Visual diff skipped via pipeline directive"
          else
            echo "should_run=true" >> $GITHUB_OUTPUT
          fi

  visual:
    name: Screenshot diff
    needs: gate
    if: needs.gate.outputs.should_run == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 20
    env:
      PREVIEW_URL: ${{ vars.PREVIEW_URL_PATTERN }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: npm
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - name: Resolve preview URL
        run: echo "PREVIEW_RESOLVED=${PREVIEW_URL//\$\{PR\}/${{ github.event.pull_request.number }}}" >> $GITHUB_ENV
      - name: Capture screenshots (PR)
        run: npx playwright test --project=visual --update-snapshots=none
        env:
          BASE_URL: ${{ env.PREVIEW_RESOLVED }}
        continue-on-error: true
      - name: Upload screenshots + diffs
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: visual-diff
          path: |
            tests/visual/__screenshots__/
            test-results/
          retention-days: 7
      - name: Comment on PR with diff link
        if: always()
        uses: actions/github-script@v7
        with:
          script: |
            const run = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## Visual Diff\n\nScreenshots and diffs uploaded as artifacts: [view run](${run})\n\nIf intentional changes: update snapshots locally with \`npx playwright test --project=visual --update-snapshots\` and commit.`
            });
