name: Release PR

on:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write
  issues: write

concurrency:
  group: release-pr-${{ github.ref }}
  cancel-in-progress: true

jobs:
  release-pr:
    runs-on: ubuntu-latest
    outputs:
      cli_release_created: ${{ steps.release.outputs.release_created }}
      cli_tag_name: ${{ steps.release.outputs.tag_name }}

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Detect release PR merge
        id: detect
        run: |
          MSG=$(git log -1 --format=%s)
          if [[ "$MSG" == chore:\ release* ]]; then
            echo "is_release_merge=true" >> "$GITHUB_OUTPUT"
          else
            echo "is_release_merge=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Validate release metadata scripts
        if: steps.detect.outputs.is_release_merge == 'false'
        run: bun run release:validate

      - name: Maintain release PR
        id: release
        uses: googleapis/release-please-action@v4.4.0
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          config-file: .github/release-please-config.json
          manifest-file: .github/.release-please-manifest.json
          skip-labeling: false

  publish-cli:
    needs: release-pr
    if: needs.release-pr.outputs.cli_release_created == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write

    concurrency:
      group: publish-${{ needs.release-pr.outputs.cli_tag_name }}
      cancel-in-progress: false

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: ${{ needs.release-pr.outputs.cli_tag_name }}

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Run tests
        run: bun test

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

      - name: Publish package
        run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
