name: Publish to npm

on:
  push:
    tags:
      - 'v*'

jobs:
  npm-publish:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Install pnpm
        run: npm install -g pnpm

      - name: Update package.json version to match tag
        run: |
          TAG_VERSION=${GITHUB_REF#refs/tags/v}
          PACKAGE_VERSION=$(node -p "require('./package.json').version")

          if [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then
            echo "Updating package.json version from $PACKAGE_VERSION to $TAG_VERSION"
            npm version $TAG_VERSION --no-git-tag-version

            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"
            git add package.json
            git commit -m "chore: bump version to $TAG_VERSION for npm publish [skip ci]"
            git push origin HEAD:main
          else
            echo "✓ Version already matches: v$TAG_VERSION"
          fi

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build project
        run: pnpm build

      - name: Publish to npm
        run: pnpm publish --no-git-checks
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
