name: Publish to npm

on:
  push:
    branches: [master]

jobs:
  publish:
    runs-on: ubuntu-latest
    if: "!startsWith(github.event.head_commit.message, 'v')"
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v6

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

      - name: Determine version bump
        id: version
        # Never inline `${{ github.event.head_commit.message }}` into the
        # script body — GitHub Actions substitutes it BEFORE the shell runs,
        # so backticks / parens / `${...}` / `{vars}` get evaluated as
        # commands. Always pass via env: so it lands as a quoted string.
        env:
          COMMIT_MSG: ${{ github.event.head_commit.message }}
        run: |
          if echo "$COMMIT_MSG" | grep -qw "\[major\]"; then
            echo "bump=major" >> $GITHUB_OUTPUT
          elif echo "$COMMIT_MSG" | grep -qw "\[minor\]"; then
            echo "bump=minor" >> $GITHUB_OUTPUT
          else
            echo "bump=patch" >> $GITHUB_OUTPUT
          fi

      - name: Sync version from npm and bump
        run: |
          # Get latest version from npm, fallback to package.json
          NPM_VERSION=$(npm view expo-app-blocker version 2>/dev/null || echo "0.0.0")
          echo "Current npm version: $NPM_VERSION"
          # Set package.json to npm version first
          npm version $NPM_VERSION --no-git-tag-version --allow-same-version
          # Then bump
          npm version ${{ steps.version.outputs.bump }} --no-git-tag-version
          NEW_VERSION=$(node -p 'require("./package.json").version')
          echo "New version: $NEW_VERSION"
          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
        id: bump

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

      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh release create "v${{ steps.bump.outputs.new_version }}" --target "$GITHUB_SHA" --generate-notes
