name: Publish to npm

# Publishes @agility/management-sdk to npm when a version tag (vX.Y.Z) is pushed.
#
# Release flow:
#   1. Bump "version" in package.json and merge to main.
#   2. Tag the commit: `git tag v0.1.40 && git push origin v0.1.40`
#   3. This workflow verifies the tag matches package.json, builds, and publishes.

on:
  push:
    tags:
      - "v*"

jobs:
  publish:
    name: Build and publish to npm
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write # required for npm Trusted Publisher (OIDC) provenance

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Verify tag matches package.json version
        run: |
          TAG_VERSION="${GITHUB_REF_NAME#v}"
          PKG_VERSION=$(node -p "require('./package.json').version")
          if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then
            echo "Tag ($TAG_VERSION) does not match package.json version ($PKG_VERSION)."
            exit 1
          fi

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"

      - name: Upgrade npm for Trusted Publisher OIDC support
        run: npm install -g npm@latest

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Publish
        run: |
          PKG_VERSION=$(node -p "require('./package.json').version")
          PRERELEASE_TAG=$(echo "$PKG_VERSION" | grep -oP '(?<=-)\w+' | head -1 || true)
          if [ -n "$PRERELEASE_TAG" ]; then
            npm publish --access public --provenance --tag "$PRERELEASE_TAG"
          else
            npm publish --access public --provenance
          fi
