name: Release and Publish

on:
  release:
    types: [published]

# Add permissions block to grant write access
permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18
          registry-url: 'https://registry.npmjs.org/'
          always-auth: true

      - name: Install dependencies
        run: npm install

      - name: Configure Git user
        run: |
          git config user.name "${GITHUB_ACTOR}"
          git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"

      # Replace the complex version extraction with a simpler approach
      - name: Extract version from tag
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV

      - name: Update package.json version
        run: npm --no-git-tag-version version $VERSION

      # Remove the git push step since we're in a detached HEAD state
      # and we only need to update the version for publishing to npm

      - name: Run build
        run: npm run build

      - name: Package npm module
        run: npm pack

      - name: Publish to npm
        run: npm publish --verbose
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
