name: Auto Delete Branch After Merge

on:
  pull_request:
    types: [closed]

jobs:
  delete-merged-branch:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    steps:
      - name: Delete merged branch
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GH_TOKEN }}
          script: |
            const base = context.payload.pull_request.base.ref;
            const head = context.payload.pull_request.head.ref;
            const owner = context.repo.owner;
            const repo = context.repo.repo;

            core.info(`Check Deletion for: ${head} (merged into ${base})`);

            // Protected Patterns
            const protectedPrefixes = ["dev_", "preprod_", "master_", "main"];
            
            // Check if head branch is protected
            const isProtected = protectedPrefixes.some(prefix => head.startsWith(prefix));

            if (isProtected) {
              core.info(`🛡️ Branch '${head}' is a protected environment branch. Skipping deletion.`);
              return;
            }

            // Additional Safety: Don't delete if it's not a standard feature/fix pattern?
            // User wants to clean up users branches.
            
            try {
              core.info(`🧹 Deleting branch: ${head}`);
              await github.rest.git.deleteRef({
                owner,
                repo,
                ref: `heads/${head}`
              });
              core.info("✅ Branch deleted successfully.");
            } catch (error) {
              core.warning(`Failed to delete branch: ${error.message}`);
            }