name: auto-retarget-main-pr-to-dev

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - edited
    branches:
      - main

permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  retarget:
    if: github.actor != 'github-actions[bot]'
    runs-on: ubuntu-latest
    steps:
      - name: Retarget PR base to dev
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            const prNumber = pr.number;
            const { owner, repo } = context.repo;

            const baseRef = pr.base?.ref;
            const headRef = pr.head?.ref;
            const desiredBase = "dev";

            if (baseRef !== "main") {
              core.info(`PR #${prNumber} base is ${baseRef}; nothing to do.`);
              return;
            }

            if (headRef === desiredBase) {
              core.info(`PR #${prNumber} is ${desiredBase} -> main; skipping retarget.`);
              return;
            }

            core.info(`Retargeting PR #${prNumber} base from ${baseRef} to ${desiredBase}.`);

            try {
              await github.rest.pulls.update({
                owner,
                repo,
                pull_number: prNumber,
                base: desiredBase,
              });
            } catch (error) {
              core.setFailed(`Failed to retarget PR #${prNumber} to ${desiredBase}: ${error.message}`);
              return;
            }

            const body = [
              `This pull request targeted \`${baseRef}\`.`,
              "",
              `The base branch has been automatically changed to \`${desiredBase}\`.`,
            ].join("\n");

            try {
              await github.rest.issues.createComment({
                owner,
                repo,
                issue_number: prNumber,
                body,
              });
            } catch (error) {
              core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
            }
