name: 'E2E Sync (PR Gate)'

# Runs the SuperSync and WebDAV E2E suites on PRs, but only when code that can
# affect the respective provider changed. Both suites share one change-detection
# job and one frontend build; each has its own required status check.
#
# Why the gate/aggregator shape instead of a trigger-level `paths:` filter:
# a required status check that gets filtered out by `paths:` never reports a
# status, so unrelated PRs would hang forever waiting on a check that never runs.
# Instead this workflow ALWAYS triggers, a cheap `detect` job decides which
# suites run, and the always-running `gate-*` jobs are the checks you mark
# required in branch protection — each passes when its suite succeeded OR was
# skipped (no relevant changes).
#
# The `detect` path lists are a heuristic, not a proof: sync correctness is
# cross-cutting, so a truly exhaustive list would approach "all of src/app".
# The nightly `E2E Tests (Scheduled)` run remains the backstop for anything
# these lists miss.

on:
  pull_request:
    branches: [master, main]
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: e2e-sync-pr-${{ github.ref }}
  cancel-in-progress: true

jobs:
  # Job 0: decide which suites this PR needs. Cheap (checkout + git diff, a few
  # seconds) so it can always run and always feed the required gates.
  detect:
    name: Detect sync changes
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      supersync: ${{ steps.detect.outputs.supersync }}
      webdav: ${{ steps.detect.outputs.webdav }}
    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Detect provider-affecting changes
        id: detect
        env:
          # For workflow_dispatch there is no PR base — force both suites to run.
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          PR_HEAD: ${{ github.event.pull_request.head.sha }}
        run: |
          set -euo pipefail

          if [ -z "${BASE_SHA:-}" ]; then
            echo "No PR base (manual run) — running both suites."
            echo "supersync=true" >> "$GITHUB_OUTPUT"
            echo "webdav=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          # Net changes of THIS PR only. actions/checkout leaves HEAD at the
          # refs/pull/N/merge commit, whose parents are [live base tip (HEAD^1),
          # PR head (HEAD^2)]. Diff the PR head against its merge-base with the
          # live base. NB: do NOT diff the event-time pull_request.base.sha against
          # the merge HEAD — that sha goes stale as the base branch advances while
          # the PR is open, so the range balloons to every commit merged into the
          # base since the PR opened and trips the pattern on unrelated churn.
          BASE_TIP="$(git rev-parse HEAD^1)"
          MERGE_BASE="$(git merge-base "${BASE_TIP}" "${PR_HEAD}")"
          CHANGED_FILES="$(git diff --name-only "${MERGE_BASE}" "${PR_HEAD}")"
          echo "Changed files:"
          echo "${CHANGED_FILES}"

          # Shared: client sync code + E2E harness that both providers exercise.
          # Keep in rough sync with the nightly workflow's push `paths:` list.
          COMMON='src/app/imex/sync/|src/app/op-log/|src/app/pfapi/|src/app/root-store/|src/app/features/[^/]+/store/|packages/sync-providers/|packages/sync-core/|packages/shared-schema/|docker-compose\.yaml$|e2e/tests/sync/|e2e/helpers/|e2e/pages/|e2e/fixtures/|e2e/constants/|e2e/utils/|e2e/playwright\.config\.ts$|e2e/global-setup\.ts$|\.github/workflows/e2e-sync-pr\.yml$'
          # SuperSync also depends on the server package and its compose override.
          SUPERSYNC_PATTERN="^(${COMMON}|packages/super-sync-server/|docker-compose\.supersync\.yaml\$)"
          WEBDAV_PATTERN="^(${COMMON})"

          supersync=false
          webdav=false
          # here-string (not echo|grep) so a first-line match can't SIGPIPE the
          # upstream under `set -o pipefail`; if-condition so a no-match (grep
          # exit 1) does not trip `set -e`.
          if grep -Eq "${SUPERSYNC_PATTERN}" <<< "${CHANGED_FILES}"; then supersync=true; fi
          if grep -Eq "${WEBDAV_PATTERN}" <<< "${CHANGED_FILES}"; then webdav=true; fi

          echo "→ supersync=${supersync} webdav=${webdav}"
          echo "supersync=${supersync}" >> "$GITHUB_OUTPUT"
          echo "webdav=${webdav}" >> "$GITHUB_OUTPUT"

  # Job 1: build the frontend once, shared by both suites.
  build:
    name: Build Frontend
    needs: detect
    if: needs.detect.outputs.supersync == 'true' || needs.detect.outputs.webdav == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 15
    env:
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}
    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Setup E2E Environment
        uses: ./.github/actions/setup-e2e

      - run: npm run env

      - name: Build Frontend for E2E
        run: npm run buildFrontend:e2e

      - name: Verify Build Output
        run: |
          test -f .tmp/angular-dist/browser/index.html || (echo "Build output missing" && exit 1)
          test -f .tmp/angular-dist/browser/assets/bundled-plugins/api-test-plugin/manifest.json || (echo "Plugin assets missing from build" && exit 1)

      - name: Upload Build Artifact
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: e2e-sync-pr-build-${{ github.run_id }}
          path: .tmp/angular-dist
          retention-days: 1

  # Job 2: SuperSync E2E tests (sharded), each shard spins up its own server.
  e2e-supersync:
    name: SuperSync E2E ${{ matrix.shard }}/6
    needs: [detect, build]
    if: needs.detect.outputs.supersync == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 40
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3, 4, 5, 6]
    env:
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}
    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Setup E2E Environment
        uses: ./.github/actions/setup-e2e

      - name: Download Build Artifact
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v4
        with:
          name: e2e-sync-pr-build-${{ github.run_id }}
          path: .tmp/angular-dist

      - name: Create .env file for Docker Compose
        run: cp .env.example .env

      - name: Start SuperSync Docker Service
        # Retry to survive transient Docker Hub pull timeouts / rate limits;
        # timeout_minutes also bounds the otherwise-unbounded health-wait loop.
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          timeout_minutes: 12
          max_attempts: 3
          retry_wait_seconds: 20
          command: |
            docker compose -f docker-compose.yaml -f docker-compose.supersync.yaml up -d --build supersync
            echo "⏳ Waiting for SuperSync server..."
            until curl -s http://localhost:1901/health > /dev/null 2>&1; do sleep 1; done
            echo "✓ SuperSync server ready!"

      - name: Run SuperSync E2E Tests
        env:
          E2E_REQUIRE_SUPERSYNC: 'true'
        run: npm run e2e:all -- --grep "@supersync" --shard=${{ matrix.shard }}/6

      - name: Stop Docker Services
        if: always()
        run: docker compose -f docker-compose.yaml -f docker-compose.supersync.yaml down supersync

      - name: Print Docker Logs on Failure
        if: ${{ failure() }}
        run: |
          echo "=== SuperSync Logs ==="
          docker compose -f docker-compose.yaml -f docker-compose.supersync.yaml logs supersync

      - name: Upload E2E Results on Failure
        if: ${{ failure() }}
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: e2e-sync-pr-supersync-results-${{ matrix.shard }}-${{ github.run_id }}
          path: .tmp/e2e-test-results/**/*.*
          retention-days: 30

  # Job 3: WebDAV E2E tests (single job — the suite is small, no sharding).
  e2e-webdav:
    name: WebDAV E2E
    needs: [detect, build]
    if: needs.detect.outputs.webdav == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    env:
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}
    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Setup E2E Environment
        uses: ./.github/actions/setup-e2e

      - name: Download Build Artifact
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v4
        with:
          name: e2e-sync-pr-build-${{ github.run_id }}
          path: .tmp/angular-dist

      - name: Create .env file for Docker Compose
        run: cp .env.example .env

      - name: Start WebDAV Docker Service
        # Retry to survive transient Docker Hub pull timeouts / rate limits.
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          timeout_minutes: 6
          max_attempts: 3
          retry_wait_seconds: 20
          command: |
            docker compose up -d webdav
            chmod +x ./scripts/wait-for-webdav.sh
            ./scripts/wait-for-webdav.sh

      - name: Run WebDAV E2E Tests
        env:
          E2E_REQUIRE_WEBDAV: 'true'
        run: npm run e2e:all -- --grep "@webdav"

      - name: Stop Docker Services
        if: always()
        run: docker compose down

      - name: Print Docker Logs on Failure
        if: ${{ failure() }}
        run: |
          echo "=== WebDAV Logs ==="
          docker compose logs webdav

      - name: Upload E2E Results on Failure
        if: ${{ failure() }}
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: e2e-sync-pr-webdav-results-${{ github.run_id }}
          path: .tmp/e2e-test-results/**/*.*
          retention-days: 30

  # Job 4: SuperSync required status check. Always runs, so it always reports.
  # Mark this job's name ("SuperSync E2E Gate") required in branch protection.
  gate-supersync:
    name: SuperSync E2E Gate
    needs: [detect, e2e-supersync]
    if: always()
    runs-on: ubuntu-latest
    timeout-minutes: 2
    steps:
      - name: Evaluate result
        env:
          DETECT_RESULT: ${{ needs.detect.result }}
          CHANGED: ${{ needs.detect.outputs.supersync }}
          RESULT: ${{ needs.e2e-supersync.result }}
        run: |
          set -euo pipefail
          # Fail closed: if change detection didn't succeed we can't know whether
          # the suite was needed, so block rather than pass on an empty output.
          if [ "${DETECT_RESULT}" != "success" ]; then
            echo "✗ Change detection did not succeed (result: ${DETECT_RESULT}); cannot clear the gate."
            exit 1
          fi
          if [ "${CHANGED}" != "true" ]; then
            echo "✓ No SuperSync-affecting changes — SuperSync E2E not required for this PR."
            exit 0
          fi
          if [ "${RESULT}" = "success" ]; then
            echo "✓ SuperSync E2E passed."
            exit 0
          fi
          echo "✗ SuperSync E2E did not pass (result: ${RESULT})."
          exit 1

  # Job 5: WebDAV required status check. Always runs, so it always reports.
  # Mark this job's name ("WebDAV E2E Gate") required in branch protection.
  gate-webdav:
    name: WebDAV E2E Gate
    needs: [detect, e2e-webdav]
    if: always()
    runs-on: ubuntu-latest
    timeout-minutes: 2
    steps:
      - name: Evaluate result
        env:
          DETECT_RESULT: ${{ needs.detect.result }}
          CHANGED: ${{ needs.detect.outputs.webdav }}
          RESULT: ${{ needs.e2e-webdav.result }}
        run: |
          set -euo pipefail
          if [ "${DETECT_RESULT}" != "success" ]; then
            echo "✗ Change detection did not succeed (result: ${DETECT_RESULT}); cannot clear the gate."
            exit 1
          fi
          if [ "${CHANGED}" != "true" ]; then
            echo "✓ No WebDAV-affecting changes — WebDAV E2E not required for this PR."
            exit 0
          fi
          if [ "${RESULT}" = "success" ]; then
            echo "✓ WebDAV E2E passed."
            exit 0
          fi
          echo "✗ WebDAV E2E did not pass (result: ${RESULT})."
          exit 1
