name: Publish to npmjs

on:
  push:
    branches:
      - main
  workflow_dispatch:
    inputs:
      version-type:
        description: 'Version bump type'
        required: true
        type: choice
        options:
          - patch
          - minor
          - major
        default: patch

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - uses: actions/setup-node@v4
        with:
          node-version: '20.x'

      - run: npm ci

      - name: Build Project
        run: node scripts/build.js

      - name: Set version type
        id: version
        run: |
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            echo "type=${{ inputs.version-type }}" >> $GITHUB_OUTPUT
          else
            echo "type=patch" >> $GITHUB_OUTPUT
          fi

      - name: Bump ${{ steps.version.outputs.type }} version
        run: |
          git config --global user.name "github-actions"
          git config --global user.email "github-actions@github.com"
          npm version ${{ steps.version.outputs.type }} --no-git-tag-version
          git add package.json package-lock.json || true
          git commit -m "ci: bump ${{ steps.version.outputs.type }} version [skip ci]" || echo "No changes to commit"
          git push origin HEAD:main || echo "No changes to push"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup .npmrc for OIDC
        run: |
          cat << EOF > ~/.npmrc
          //registry.npmjs.org/:_authToken=\${NPM_TOKEN}
          registry=https://registry.npmjs.org/
          always-auth=true
          EOF

      - run: npm publish --access public
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
