name: Publish to npm

on:
  push:
    tags:
      - 'v*'

jobs:
  test-and-publish:
    runs-on: ubuntu-latest
    permissions:
      contents: write  # Required for creating releases
      id-token: write  # Required for OIDC trusted publishing
    steps:
      - uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 'lts/*'
          registry-url: 'https://registry.npmjs.org'

      - name: Install pnpm
        uses: pnpm/action-setup@v6

      - name: Install npm v11.6.2 (required for OIDC trusted publishing, min v11.5.1)
        run: npm install -g npm@11.6.2

      - name: Install dependencies
        run: pnpm install

      - name: Build workspace packages
        run: pnpm -r run build

      - name: Run tests
        run: pnpm test

      - name: Build
        run: pnpm run build

      - name: Publish @myerscarpenter/cast2-protocol (skip if version already published)
        working-directory: packages/cast2-protocol
        run: |
          PKG_NAME=$(node -p "require('./package.json').name")
          PKG_VERSION=$(node -p "require('./package.json').version")
          if npm view "${PKG_NAME}@${PKG_VERSION}" version >/dev/null 2>&1; then
            echo "${PKG_NAME}@${PKG_VERSION} already published, skipping"
          else
            if [[ "${{ github.ref_name }}" == *-* ]]; then
              pnpm publish --tag next --provenance --access public --no-git-checks
            else
              pnpm publish --provenance --access public --no-git-checks
            fi
          fi

      - name: Publish @myerscarpenter/quest-dev
        run: |
          if [[ "${{ github.ref_name }}" == *-* ]]; then
            pnpm publish --tag next --provenance --access public --no-git-checks
          else
            pnpm publish --provenance --access public --no-git-checks
          fi

      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
          if [ -n "$PREV_TAG" ]; then
            NOTES=$(git log --pretty=format:"- %s" "$PREV_TAG"..HEAD^)
          else
            NOTES="Initial release"
          fi
          if [[ "${{ github.ref_name }}" == *-* ]]; then
            gh release create "${{ github.ref_name }}" --notes "$NOTES" --prerelease
          else
            gh release create "${{ github.ref_name }}" --notes "$NOTES"
          fi
