name: Bump & Publish

on:
  push:
    branches: [main]

permissions:
  contents: write

jobs:
  bump-and-publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Configure git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Bump patch version
        run: |
          git fetch --tags --force
          HIGHEST=$(git tag -l 'v[0-9]*' | sort -V | tail -1 | sed 's/^v//')
          CURRENT=$(node -p "require('./package.json').version")
          BASE="$HIGHEST"
          if [ -z "$BASE" ] || [ "$(printf '%s\n%s' "$CURRENT" "$BASE" | sort -V | tail -1)" = "$CURRENT" ]; then BASE="$CURRENT"; fi
          node -e "const p=require('./package.json');p.version='$BASE';require('fs').writeFileSync('./package.json', JSON.stringify(p,null,2)+'\n')"
          NEW_VERSION=$(npm version patch --no-git-tag-version)
          while git rev-parse "$NEW_VERSION" >/dev/null 2>&1; do
            echo "tag $NEW_VERSION exists, bumping again"
            NEW_VERSION=$(npm version patch --no-git-tag-version)
          done
          git add package.json
          git commit -m "chore: bump to ${NEW_VERSION}"
          git tag "${NEW_VERSION}"
          git push origin main --tags

      - run: npm install

      - name: Publish to npm
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
