name: Publish to NPM
on:
  release:
    types: [ published ]

jobs:
  bump-version:
    runs-on: ubuntu-latest
    steps:
      - name: Generate GitHub App token
        id: generate-token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ vars.SDK_GENERATION_APP_ID }}
          private-key: ${{ secrets.SDK_GENERATION_APP_PRIVATE_KEY }}

      - name: Check out repository code
        uses: actions/checkout@v4
        with:
          token: ${{ steps.generate-token.outputs.token }}

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: |
          npm install
          npm i -g auto-changelog

      - name: Bump version and add changelog
        env:
          # Passed via env, never interpolated into the script: a git tag name may legally contain
          # ; $ ` & | ( ), so inlining it in the script would let a crafted release tag run commands.
          INITIAL_TAG: ${{ github.event.release.tag_name }}
        run: |
          tag="${INITIAL_TAG//[v]/}"
          echo "$tag"
          git remote update
          git fetch
          git checkout --track origin/master
          git config --global user.email "github-actions@github.com"
          git config --global user.name "Github Actions"
          npm --no-git-tag-version --allow-same-version version "$tag"
          auto-changelog
          git add .
          git commit -m "release $tag"
          git push

      - name: Move tag
        env:
          TAG_NAME: ${{ github.event.release.tag_name }}
        run: |
          echo "$TAG_NAME"
          git tag --force "$TAG_NAME"
          git push --force origin "$TAG_NAME"

  publish:
    needs: bump-version
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Required for OIDC/Trusted Publishing
      contents: read
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.release.tag_name }}
          fetch-depth: 0

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

      - name: Ensure npm 11.5.1+
        run: npm install -g npm@^11

      - name: Install dependencies
        run: npm install

      - name: Publish package
        run: npm publish
        # No NODE_AUTH_TOKEN needed - OIDC handles authentication
