name: 'Util: Backport pull request changes'

run-name: Backport pull request ${{ github.event.pull_request.number || inputs.pull-request-id }}

on:
  pull_request:
    types: [closed]
  workflow_dispatch:
    inputs:
      pull-request-id:
        description: 'The ID number of the pull request (e.g. 3342). No #, no extra letters.'
        required: true
        type: string

permissions:
  contents: write
  pull-requests: write

jobs:
  backport:
    if: |
      github.event.pull_request.merged == true ||
      github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-slim
    outputs:
      created_pull_numbers: ${{ steps.backport.outputs.created_pull_numbers }}
    steps:
      - name: Generate GitHub App Token
        id: generate-token
        uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1
        with:
          app-id: ${{ secrets.N8N_ASSISTANT_APP_ID }}
          private-key: ${{ secrets.N8N_ASSISTANT_PRIVATE_KEY }}

      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          token: ${{ steps.generate-token.outputs.token }}
          fetch-depth: 1

      - 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: Compute backport targets
        id: targets
        env:
          PULL_REQUEST_ID: ${{ inputs.pull-request-id }}
          GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
        run: node .github/scripts/compute-backport-targets.mjs

      - name: Backport
        id: backport
        if: steps.targets.outputs.target_branches != ''
        uses: korthout/backport-action@4aaf0e03a94ff0a619c9a511b61aeb42adea5b02 # v4.2.0
        with:
          github_token: ${{ steps.generate-token.outputs.token }}
          source_pr_number: ${{ github.event.pull_request.number || inputs.pull-request-id }}
          target_branches: ${{ steps.targets.outputs.target_branches }}
          pull_description: |-
            # Description
            Backport of #${pull_number} to `${target_branch}`.

            ## Checklist for the author (@${pull_author}) to go through.

            - [ ] Review the backport changes
            - [ ] Fix possible conflicts
            - [ ] Merge to target branch

            After this PR has been merged, it will be picked up in the next patch release for release track.

            # Original description

            ${pull_description}
          pull_title: ${pull_title} (backport to ${target_branch})
          add_author_as_assignee: true
          add_author_as_reviewer: true
          copy_assignees: true
          copy_requested_reviewers: false
          copy_labels_pattern: '^(?!Backport to\b).+' # Copy everything except backport labels
          add_labels: 'automation:backport'
          experimental: >
            {
              "conflict_resolution": "draft_commit_conflicts"
            }

  prepare-auto-merge:
    needs: [backport]
    if: needs.backport.outputs.created_pull_numbers != ''
    runs-on: ubuntu-slim
    outputs:
      pr_numbers_json: ${{ steps.filter.outputs.pr_numbers_json }}
    steps:
      - name: Filter out draft PRs
        id: filter
        env:
          PR_NUMBERS: ${{ needs.backport.outputs.created_pull_numbers }}
          GH_TOKEN: ${{ github.token }}
          REPOSITORY: ${{ github.repository }}
        run: |
          set -euo pipefail
          mergeable_json="[]"
          for pr in $PR_NUMBERS; do
            is_draft=$(gh pr view "$pr" --repo "$REPOSITORY" --json isDraft --jq '.isDraft')
            if [ "$is_draft" = "true" ]; then
              echo "Skipping draft PR #$pr (conflicts to resolve)"
            else
              mergeable_json=$(echo "$mergeable_json" | jq -c --arg pr "$pr" '. + [$pr]')
            fi
          done
          echo "pr_numbers_json=$mergeable_json" >> "$GITHUB_OUTPUT"

  auto-merge-successful-backports:
    needs: [prepare-auto-merge]
    if: needs.prepare-auto-merge.outputs.pr_numbers_json != '[]'
    strategy:
      fail-fast: false
      matrix:
        pr_number: ${{ fromJSON(needs.prepare-auto-merge.outputs.pr_numbers_json) }}
    uses: ./.github/workflows/util-approve-and-set-automerge.yml
    with:
      pull-request-number: ${{ matrix.pr_number }}
    secrets: inherit

