name: Query Counts

on:
  pull_request:
    branches: [main]

# Runs with the default read-only token; this workflow never pushes or
# comments. The companion "Query Counts — Apply" workflow (triggered by
# workflow_run) handles that with elevated permissions, safely isolated
# from PR-authored code.
permissions:
  contents: read

jobs:
  measure:
    name: Measure
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          persist-credentials: false
      - uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
      - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: 22
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm build

      - name: Regenerate snapshots
        run: |
          node scripts/query-counts.mjs --target sqlite --update
          node scripts/query-counts.mjs --target d1 --update

      - name: Detect snapshot drift
        id: drift
        run: |
          mkdir -p query-counts-out
          # Track both the count snapshots and the query-text snapshots. The
          # query-text files (.queries.*.json) record the actual SQL per route;
          # without them here a change that alters a query's text but not the
          # count (e.g. adding a column to a folded subquery) would never be
          # committed back, leaving the D1 text snapshot silently stale.
          counts="scripts/query-counts.snapshot.sqlite.json scripts/query-counts.snapshot.d1.json"
          queries="scripts/query-counts.queries.sqlite.json scripts/query-counts.queries.d1.json"
          if git diff --quiet $counts $queries; then
            echo "changed=false" >> "$GITHUB_OUTPUT"
            echo "No drift — snapshots match the committed baseline."
          else
            echo "changed=true" >> "$GITHUB_OUTPUT"
            cp $counts $queries query-counts-out/
            git diff $counts $queries > query-counts-out/snapshots.diff
            echo "${{ github.event.pull_request.number }}" > query-counts-out/pr-number
            echo "Drift detected — uploading artifact for the Apply workflow."
            # Log only the count diff; the query-text diffs can be large and
            # are carried in the artifact for the Apply workflow to commit.
            git diff $counts
          fi

      - name: Upload snapshot artifact
        if: steps.drift.outputs.changed == 'true'
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: query-counts-snapshots
          path: query-counts-out/
          retention-days: 7
          if-no-files-found: error
