name: Publish Package to NPM

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to publish (e.g., 1.0.0, patch, minor, major)'
        required: true
        default: 'patch'
      tag:
        description: 'NPM tag (e.g., latest, beta, next)'
        required: true
        default: 'latest'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          # This ensures complete repo history for version management
          fetch-depth: 0
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20.x'
          registry-url: 'https://registry.npmjs.org'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Set custom version
        id: set-version
        run: |
          # For semantic versioning keywords (patch, minor, major)
          if [[ "${{ github.event.inputs.version }}" =~ ^(patch|minor|major)$ ]]; then
            npm version ${{ github.event.inputs.version }} --no-git-tag-version
          # For explicit versions (e.g., 1.0.0)
          else
            npm version ${{ github.event.inputs.version }} --no-git-tag-version --allow-same-version
          fi
          echo "new_version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
      
      - name: Build package
        run: npm run build
      
      - name: Run tests
        run: npm test
      
      - name: Publish to NPM
        run: npm publish --tag ${{ github.event.inputs.tag }}
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      
      - name: Create Git tag
        run: |
          git config --local user.email "hello@nclsndr.com"
          git config --local user.name "nclsndr"
          git tag -a v${{ steps.set-version.outputs.new_version }} -m "Release v${{ steps.set-version.outputs.new_version }}"
          git push origin v${{ steps.set-version.outputs.new_version }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 