name: Publish Package to NPM

on:
  release:
    types: [published]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Use Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20.x'
          registry-url: 'https://registry.npmjs.org'
          cache: 'npm'

      - name: Update version in package.json
        run: |
          # Get version from GitHub release tag
          VERSION=${GITHUB_REF_NAME#v}
          echo "Updating to version: $VERSION"
          # Update package.json version
          npm version $VERSION --no-git-tag-version --allow-same-version

      - name: Install dependencies
        run: npm ci
        
      - name: Build
        run: npm run build --if-present
        
      - name: Publish to NPM
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
