name: 'Util: Approve and set Automerge'

run-name: Approve and automerge PR ${{ inputs.pull-request-number }}

on:
  workflow_call:
    inputs:
      pull-request-number:
        type: string
        required: true

permissions:
  contents: write
  pull-requests: write

jobs:
  approve-and-automerge:
    if: |
      inputs.pull-request-number != ''
    runs-on: ubuntu-slim
    environment: release
    steps:
      - name: Generate GitHub App Token
        id: generate-token
        uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1
        with:
          app-id: ${{ secrets.N8N_RELEASE_HELPER_APP_ID }}
          private-key: ${{ secrets.N8N_RELEASE_HELPER_PRIVATE_KEY }}

      - name: Approve PR (as the App)
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
          PR_NUMBER: ${{ inputs.pull-request-number }}
          REPOSITORY: ${{ github.repository }}
        run: |
          gh pr review "$PR_NUMBER" \
            --approve \
            --repo "$REPOSITORY"

      - name: Enable auto-merge (merge when checks pass)
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
          PR_NUMBER: ${{ inputs.pull-request-number }}
          REPOSITORY: ${{ github.repository }}
        run: |
          gh pr merge "$PR_NUMBER" \
            --auto \
            --squash \
            --repo "$REPOSITORY"
