# Enable GitHub auto-merge for Dependabot PRs after required checks pass.
# Semver-major grouped npm/docs updates are excluded (merge manually after review).
# Repo setting "Allow auto-merge" + branch protection with required checks must be enabled (see docs/github/SETUP.md).
name: Dependabot auto-merge

on:
  pull_request:
    branches: [main]
    types: [opened, synchronize, reopened, ready_for_review]

permissions:
  contents: write
  pull-requests: write

concurrency:
  group: dependabot-auto-merge-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  enable-auto-merge:
    runs-on: ubuntu-latest
    if: github.actor == 'dependabot[bot]'
    steps:
      - name: Dependabot metadata
        id: metadata
        uses: dependabot/fetch-metadata@v2
        with:
          github-token: "${{ secrets.GITHUB_TOKEN }}"

      - name: Semver-major — manual merge only
        if: ${{ !startsWith(github.head_ref, 'dependabot/github_actions/') && steps.metadata.outputs.update-type == 'version-update:semver-major' }}
        run: echo "::notice::Dependabot semver-major grouped update — auto-merge disabled; merge manually."

      - name: Enable auto-merge (squash)
        if: ${{ startsWith(github.head_ref, 'dependabot/github_actions/') || steps.metadata.outputs.update-type != 'version-update:semver-major' }}
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          REPO="${{ github.repository }}"
          PR="${{ github.event.pull_request.number }}"
          if gh pr merge "$PR" --repo "$REPO" --auto --squash; then
            exit 0
          fi
          state=$(gh pr view "$PR" --repo "$REPO" --json autoMergeRequest --jq '.autoMergeRequest.enabledAt != null' 2>/dev/null || echo "false")
          if [ "$state" = "true" ]; then
            exit 0
          fi
          exit 1
