name: Release

on:
  push:
    branches:
      - main

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  id-token: write
  contents: write
  pull-requests: write
  issues: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6
      - name: Prepare repository
        run: git fetch --unshallow --tags
      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"
      # Ensure npm 11.5.1 or later is installed
      - name: Update npm
        run: npm install -g npm@latest
      - uses: oven-sh/setup-bun@v2
        name: Install Bun
      - uses: actions/cache@v5
        name: Setup Bun cache
        with:
          path: ~/.bun/install/cache
          key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
          restore-keys: |
            ${{ runner.os }}-bun-
      - name: Install dependencies
        run: bun install
      - name: Run tests
        run: bun run test
      - name: Build dist
        run: bun run build
      - name: Create Release PR or Publish
        id: changesets
        uses: changesets/action@v1
        with:
          version: npm run changeset version
          publish: npm run changeset publish
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: "" # Workaround for https://github.com/changesets/action/pull/545
      # Consumers pin `uses: PunGrumpy/cursor-action@v1`, so the major tag has to
      # follow every release. Changesets only creates the exact `vX.Y.Z` tag.
      - name: Move major version tag
        if: steps.changesets.outputs.published == 'true'
        run: |
          set -euo pipefail
          VERSION="v$(node -p "require('./package.json').version")"
          MAJOR="${VERSION%%.*}"
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git tag -f "$MAJOR" "$VERSION"
          git push -f origin "refs/tags/$MAJOR"
          echo "Moved $MAJOR to $VERSION"
