name: Release

on:
  push:
    branches:
      - 'changeset-release/main'
      - 'changeset-release/next-major'

jobs:
  release-candidate:
    if: github.ref_name == 'changeset-release/main'
    name: Candidate (@next)
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
          fetch-depth: 0

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'npm'
      - run: npm i -g npm@^10.5.1

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Create .npmrc
        run: |
          registry="//registry.npmjs.org/"
          cat << EOF > "$HOME/.npmrc"
            $registry:_authToken=$NPM_TOKEN
          EOF
        env:
          NPM_TOKEN: ${{ secrets.NPM_AUTH_TOKEN_SHARED }}

      - name: Publish release candidate
        run: |
          pkg_json_path=packages/react/package.json
          version=$(jq -r .version $pkg_json_path)
          echo "$( jq ".version = \"$(echo $version)-rc.$(git rev-parse --short HEAD)\"" $pkg_json_path )" > $pkg_json_path
          npx changeset publish --tag next
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Output candidate version
        uses: actions/github-script@v4.0.2
        with:
          script: |
            const package = require(`${process.env.GITHUB_WORKSPACE}/packages/react/package.json`)
            github.repos.createCommitStatus({
              owner: context.repo.owner,
              repo: context.repo.repo,
              sha: context.sha,
              state: 'success',
              context: `Published ${package.name}`,
              description: package.version,
              target_url: `https://unpkg.com/${package.name}@${package.version}/`
            })

  release-candidate-next-major:
    if: github.ref_name == 'changeset-release/next-major'
    name: Candidate (@next-major)
    uses: primer/.github/.github/workflows/release_candidate.yml@v2.0.0
    with:
      tag: next-major
    secrets:
      gh_token: ${{ secrets.GITHUB_TOKEN }}
      npm_token: ${{ secrets.NPM_AUTH_TOKEN_SHARED }}