name: Dependabot update - test and merge

on:
  pull_request_target:
    types: [opened, reopened, synchronize]

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

jobs:
  test:
    name: Run unit tests (Dependabot PR)
    if: github.actor == 'dependabot[bot]'
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Check out PR head
        uses: actions/checkout@v5
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          persist-credentials: false

      - name: Set up Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Cache cargo build
        uses: Swatinem/rust-cache@v2

      - name: Run unit tests
        run: cargo test --all --locked --verbose

  merge:
    name: Approve and merge
    needs: test
    if: needs.test.result == 'success' && github.actor == 'dependabot[bot]'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Approve PR
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            await github.rest.pulls.createReview({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: pr.number,
              event: 'APPROVE',
              body: 'Automated approval: tests passed for Dependabot update.'
            });

      - name: Merge PR
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            try {
              await github.rest.pulls.merge({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: pr.number,
                merge_method: 'merge'
              });
              core.info('PR merged successfully.');
            } catch (e) {
              core.setFailed('Failed to merge PR: ' + e.message);
            }
