name: Staging Promotion Metadata

on:
  workflow_dispatch:
    inputs:
      pr_number:
        description: "Staging promotion PR number to refresh"
        required: true
        type: string
      dry_run:
        description: "Compute the body update without editing the PR"
        required: false
        type: boolean
        default: true
  pull_request_target:
    types: [opened, synchronize, reopened]
  push:
    branches:
      - main

permissions:
  contents: read
  pull-requests: write

jobs:
  refresh-single-pr:
    if: >
      (github.event_name == 'pull_request_target' &&
       github.event.pull_request.head.repo.full_name == github.repository &&
       startsWith(github.event.pull_request.head.ref, 'staging-promote/')) ||
      github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout workflow source
        uses: actions/checkout@v6
        with:
          # For chained promotion PRs, the script lives on the trusted PR head,
          # not necessarily on the older promotion branch used as the PR base.
          ref: ${{ github.event_name == 'workflow_dispatch' && 'main' || github.event.pull_request.head.sha }}
          fetch-depth: 0
          fetch-tags: true

      - name: Refresh staging promotion PR body
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event.pull_request.number }}
          REPO: ${{ github.repository }}
          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || 'false' }}
        run: bash .github/scripts/update-staging-promotion-body.sh

  refresh-open-prs-after-main-push:
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout main
        uses: actions/checkout@v6
        with:
          ref: main
          fetch-depth: 0
          fetch-tags: true

      - name: Refresh all open staging promotion PR bodies
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          REPO: ${{ github.repository }}
        run: |
          # ubuntu-latest uses bash 5.x, so mapfile is available here.
          mapfile -t prs < <(gh pr list --repo "${REPO}" --label staging-promotion --state open \
            --json number,headRefName \
            --jq '.[] | select(.headRefName | startswith("staging-promote/")) | .number')
          if [ "${#prs[@]}" -eq 0 ]; then
            echo "No open staging promotion PRs to refresh."
            exit 0
          fi
          for pr in "${prs[@]}"; do
            echo "Refreshing staging promotion PR #${pr}"
            PR_NUMBER="${pr}" bash .github/scripts/update-staging-promotion-body.sh
          done
