name: Publish

on:
  push:
    tags: ['v*']

jobs:
  publish:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      id-token: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Update npm
        run: npm install -g npm@latest

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Run tests
        run: npm test

      - name: TypeScript check
        run: npx tsc --noEmit

      - name: Verify version matches tag
        run: |
          PKG_VERSION=$(node -p "require('./package.json').version")
          TAG_VERSION=${GITHUB_REF_NAME#v}
          if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then
            echo "❌ package.json version ($PKG_VERSION) does not match tag ($TAG_VERSION)"
            echo "Run: npm run release -- $TAG_VERSION, commit, then re-push the tag."
            exit 1
          fi
          echo "✅ Version check passed: $PKG_VERSION"

      - name: Publish to npm
        run: npm publish --access public
