# Test on PR; publish @coti-io/coti-contracts via npm Trusted Publishing (OIDC) on tags — no npm_token secret.
# On npmjs: Package → Settings → Trusted publishing → GitHub Actions. Match owner, repo, and workflow filename
# exactly: npm-publish.yml (see https://docs.npmjs.com/trusted-publishers).

name: Node.js Package

on:
  workflow_dispatch:
  release:
    types: [ created ]
  pull_request:
    types: [ review_requested ]

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v5
        with:
          node-version: 16
      - run: npm ci

  update-version-and-publish:
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v5
      - name: Update package.json version from tag
        run: |
          TAG_NAME=$(echo ${{github.ref_name}})
          jq --arg tag "$TAG_NAME" '.version = $tag' package.json > tmp.$$.json && mv tmp.$$.json package.json
      - name: Commit and push changes
        run: |
          TAG_NAME=$(echo ${{github.ref_name}})
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'
          git add package.json
          git add package-lock.json
          git commit -m "Update package.json version to $TAG_NAME"
          git tag -f $TAG_NAME
          git push --force origin $TAG_NAME
        env:
          GITHUB_TOKEN: ${{ github.token }}
      - uses: actions/setup-node@v5
        with:
          node-version: '24'
          registry-url: 'https://registry.npmjs.org'
          scope: '@coti-io'
      - run: npm ci
      - run: npm publish --access=public
