name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: read
  # Required for npm provenance (OIDC).
  id-token: write

jobs:
  publish:
    name: Build & publish to npm
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org
          cache: npm

      # Trusted Publishing (OIDC) requires npm >= 11.5.1.
      - name: Upgrade npm
        run: npm install -g npm@latest

      - name: Install dependencies
        run: npm ci

      - name: Verify tag matches package.json version
        run: |
          PKG_VERSION="$(node -p "require('./package.json').version")"
          TAG_VERSION="${GITHUB_REF_NAME#v}"
          if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then
            echo "::error::Tag $GITHUB_REF_NAME ($TAG_VERSION) does not match package.json version ($PKG_VERSION)"
            exit 1
          fi
          echo "Publishing version $PKG_VERSION"

      - name: Lint
        run: npm run lint

      - name: Type check
        run: npm run check

      - name: Build
        run: npm run build

      # Publishes via Trusted Publishing (OIDC) — no NPM_TOKEN needed.
      - name: Publish to npm
        run: npm publish --provenance --access public
