name: Publish to npm

on:
  push:
    branches:
      - main

jobs:
  publish:
    if: "!contains(github.event.head_commit.message, '[skip ci]')"
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - uses: actions/setup-node@v4
        with:
          node-version: '24'
          registry-url: 'https://registry.npmjs.org'

      - run: npm ci

      - name: Determine version bump
        id: bump
        run: |
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          if [ -z "$LAST_TAG" ]; then
            COMMITS=$(git log --pretty=format:"%s%n%b")
          else
            COMMITS=$(git log ${LAST_TAG}..HEAD --pretty=format:"%s%n%b")
          fi

          BUMP=patch
          if echo "$COMMITS" | grep -qE "^feat(\(.+\))?[!]?:"; then
            BUMP=minor
          fi
          if echo "$COMMITS" | grep -qE "BREAKING CHANGE|^[a-z]+(\(.+\))?!:"; then
            BUMP=major
          fi

          echo "bump=$BUMP" >> $GITHUB_OUTPUT

      - name: Bump version and push tag
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git checkout -- .
          npm version ${{ steps.bump.outputs.bump }} -m "chore: release %s [skip ci]"
          git push --follow-tags

      - name: Publish to npm
        run: npm publish --provenance --access public

      - name: Create GitHub release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          VERSION=$(node -p "require('./package.json').version")
          gh release create "v${VERSION}" --generate-notes --title "v${VERSION}"
