name: Version bump check

# Fails any PR to main whose package.json version is not strictly greater
# (semver) than main's. No opt-out. Posts/updates one sticky comment with
# the detected bump ("2.1.6 → 2.2.0 (minor)") or fix guidance.
#
# Deliberately a separate workflow: tests.yml overwrites package.json's
# version with the npm latest tag before testing, so versions here are
# read from this job's own checkout + the GitHub contents API, never
# from the tests jobs' working trees.

on:
  pull_request:
    branches: [main]

permissions:
  contents: read
  pull-requests: write

concurrency:
  group: version-bump-check-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - name: Checkout PR head
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha }}

      - name: Compare versions
        id: compare
        continue-on-error: true # the comment step must run either way; the gate step fails the job
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          COMMENT_FILE: /tmp/version-bump-comment.md
        run: |
          BASE_VERSION=$(gh api \
            "repos/${{ github.repository }}/contents/package.json?ref=${{ github.event.pull_request.base.ref }}" \
            --jq '.content' | base64 -d | jq -r '.version')
          HEAD_VERSION=$(jq -r '.version' package.json)
          echo "Comparing base=$BASE_VERSION head=$HEAD_VERSION"
          node .github/scripts/check-version-bump.mjs "$BASE_VERSION" "$HEAD_VERSION"

      - name: Post or update sticky comment
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          MARKER='<!-- version-bump-check -->'
          COMMENT_ID=$(gh api "repos/${{ github.repository }}/issues/$PR_NUMBER/comments" \
            --paginate --jq "[.[] | select(.body | contains(\"$MARKER\"))][0].id // empty")
          if [ -n "$COMMENT_ID" ]; then
            gh api -X PATCH "repos/${{ github.repository }}/issues/comments/$COMMENT_ID" \
              -F body=@/tmp/version-bump-comment.md >/dev/null
          else
            gh api -X POST "repos/${{ github.repository }}/issues/$PR_NUMBER/comments" \
              -F body=@/tmp/version-bump-comment.md >/dev/null
          fi

      - name: Fail if version not bumped
        if: steps.compare.outcome == 'failure'
        run: |
          echo "::error::package.json version must be strictly greater than main's. See the 'Version bump check' PR comment."
          exit 1
