name: Publish

on:
  release:
    types: [created]

permissions:
  contents: read
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      # Ensure npm CLI is new enough for Trusted Publishing flows
      - run: npm i -g npm@latest
      - run: npm -v

      - run: npm ci

      # Set package.json version from the release tag (e.g. v3.2.7 -> 3.2.7)
      - name: Set version from tag
        env:
          RELEASE_TAG_NAME: ${{ github.event.release.tag_name }}
        run: |
          TAG_NAME="${RELEASE_TAG_NAME:-${GITHUB_REF_NAME}}"
          if [ -z "${TAG_NAME}" ] && [ -n "${GITHUB_REF}" ]; then
            TAG_NAME="${GITHUB_REF#refs/tags/}"
          fi

          VERSION="${TAG_NAME#v}"
          echo "RELEASE_TAG_NAME=${RELEASE_TAG_NAME}"
          echo "GITHUB_REF_NAME=${GITHUB_REF_NAME}"
          echo "GITHUB_REF=${GITHUB_REF}"
          echo "TAG_NAME=${TAG_NAME}"
          echo "VERSION=${VERSION}"
          if [ -z "${VERSION}" ]; then
            echo "Error: could not determine version from release tag/ref"
            exit 1
          fi
          npm version "${VERSION}" --no-git-tag-version --ignore-scripts

      - run: npm run build

      # Public packages sometimes need this explicitly (safe even if already public)
      - run: npm publish --access public
