name: 'Release: Create Patch Release PR'
run-name: 'Release: Create Patch Release PR for track ${{ inputs.track }}'

on:
  workflow_call:
    inputs:
      track:
        description: 'Release Track'
        required: true
        type: string

  workflow_dispatch:
    inputs:
      track:
        description: 'Release Track'
        required: true
        type: choice
        options: [stable, beta, v1]

jobs:
  determine-version-info:
    name: Determine publishing track
    runs-on: ubuntu-latest
    outputs:
      release_candidate_branch: ${{ steps.determine-branch.outputs.release_candidate_branch }}
      should_update: ${{ steps.determine-branch.outputs.should_update }}
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: ./.github/actions/setup-nodejs
        with:
          build-command: ''
          install-command: pnpm install --frozen-lockfile --dir ./.github/scripts --ignore-workspace
          cache-dependency-path: .github/scripts/pnpm-lock.yaml

      - name: Determine release candidate branch from track
        id: determine-branch
        env:
          TRACK: ${{ inputs.track }}
        run: node .github/scripts/determine-release-candidate-branch-for-track.mjs

  skip-release-pr:
    name: Skip release PR (no new commits)
    needs: [determine-version-info]
    if: needs.determine-version-info.outputs.should_update != 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Log skip reason
        run: echo "No new commits found between the release candidate branch and the current release tag. Skipping PR creation."

  create-release-pr:
    name: Create release PR
    needs: [determine-version-info]
    if: needs.determine-version-info.outputs.should_update == 'true'
    uses: ./.github/workflows/release-create-pr.yml
    secrets: inherit
    with:
      base-branch: ${{ needs.determine-version-info.outputs.release_candidate_branch }}
      release-type: patch

  notify-slack:
    name: Notify Slack
    needs: [create-release-pr]
    if: needs.create-release-pr.result == 'success' && needs.create-release-pr.outputs.pull-request-number != ''
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          sparse-checkout: .github/scripts/slack
          sparse-checkout-cone-mode: false
      - name: Notify Slack
        env:
          SLACK_TOKEN: ${{ secrets.RELEASE_HELPER_SLACK_TOKEN }}
          TRACK: ${{ inputs.track }}
          PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ needs.create-release-pr.outputs.pull-request-number }}
        run: |
          node .github/scripts/slack/notify.mjs \
            --channel C036AELNMV0 \
            --text ":rocket: Patch release PR created for *${TRACK}* track. <${PR_URL}|View PR> — close it to cancel the release."
