name: Publish to npm

on:
  push:
    branches: [main]
    paths:
      - 'package.json'

permissions:
  contents: write # Required for creating tags

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Check if version changed
        id: version_check
        run: |
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          git checkout HEAD~1 -- package.json 2>/dev/null || true
          PREVIOUS_VERSION=$(node -p "require('./package.json').version") 2>/dev/null || echo "0.0.0"
          git checkout HEAD -- package.json

          echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
          echo "previous_version=$PREVIOUS_VERSION" >> $GITHUB_OUTPUT

          if [ "$CURRENT_VERSION" != "$PREVIOUS_VERSION" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
            echo "Version changed from $PREVIOUS_VERSION to $CURRENT_VERSION"
          else
            echo "changed=false" >> $GITHUB_OUTPUT
            echo "Version unchanged ($CURRENT_VERSION)"
          fi

      - name: Setup Node.js
        if: steps.version_check.outputs.changed == 'true'
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
          registry-url: 'https://registry.npmjs.org'

      # Make sure NPM is up to date (it's not by default...)
      - name: Update npm
        if: steps.version_check.outputs.changed == 'true'
        run: npm install -g npm@latest

      - name: Install dependencies
        if: steps.version_check.outputs.changed == 'true'
        run: npm ci

      - name: Publish to npm
        if: steps.version_check.outputs.changed == 'true'
        run: npm publish --access public --provenance=false
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}

      - name: Create git tag
        if: steps.version_check.outputs.changed == 'true'
        run: |
          VERSION="v${{ steps.version_check.outputs.current_version }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a "$VERSION" -m "Release $VERSION"
          git push origin "$VERSION"
