name: Dependabot Auto-merge

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - synchronize
      - ready_for_review

permissions:
  contents: write
  pull-requests: write

jobs:
  auto-approve-and-enable-automerge:
    if: github.event.pull_request.user.login == 'dependabot[bot]' && github.event.pull_request.draft == false
    runs-on: ubuntu-latest
    timeout-minutes: 5

    steps:
      - name: Auto-approve Dependabot PR
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const { owner, repo } = context.repo;
            const pull_number = context.payload.pull_request.number;

            try {
              await github.rest.pulls.createReview({
                owner,
                repo,
                pull_number,
                event: 'APPROVE',
                body: 'Auto-approving Dependabot dependency update after CI checks.'
              });
              core.info(`Approved PR #${pull_number}`);
            } catch (error) {
              if (error.status === 422) {
                core.info(`Approval not needed or already present for PR #${pull_number}`);
              } else {
                throw error;
              }
            }

      - name: Enable auto-merge for Dependabot PR
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const pullRequestId = context.payload.pull_request.node_id;

            try {
              await github.graphql(
                `mutation($pullRequestId: ID!) {
                  enablePullRequestAutoMerge(input: {
                    pullRequestId: $pullRequestId,
                    mergeMethod: SQUASH
                  }) {
                    pullRequest {
                      number
                      autoMergeRequest {
                        enabledAt
                      }
                    }
                  }
                }`,
                { pullRequestId }
              );

              core.info(`Enabled auto-merge for PR #${context.payload.pull_request.number}`);
            } catch (error) {
              if (String(error.message).includes('already enabled')) {
                core.info(`Auto-merge already enabled for PR #${context.payload.pull_request.number}`);
              } else {
                throw error;
              }
            }
