name: 'CI: Check merge source and destination'

on:
  pull_request:
    branches:
      - master
      - 1.x

permissions:
  pull-requests: write
  contents: read

jobs:
  check_branch:
    if: ${{ github.repository == 'n8n-io/n8n-private' }}
    name: enforce-bundle-branches-only-in-private
    runs-on: ubuntu-latest

    steps:
      - name: Validate head branch
        id: validate
        shell: bash
        env:
          HEAD_REF: ${{ github.head_ref }}
        run: |
          set -euo pipefail
          head="$HEAD_REF"
          if [[ "$head" == bundle/* ]]; then
            echo "allowed=true" >> "$GITHUB_OUTPUT"
          else
            echo "allowed=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Comment on PR (blocked)
        if: ${{ steps.validate.outputs.allowed == 'false' }}
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
        with:
          script: |
            const owner = context.repo.owner;
            const repo = context.repo.repo;
            const issue_number = context.payload.pull_request.number;
            const head = context.payload.pull_request.head.ref;
            const base = context.payload.pull_request.base.ref;

            const marker = "<!-- bundle-branch-only -->";
            const body =
              `${marker}\n` +
              `🚫 **Merge blocked**: PRs into \`${base}\` are only allowed from branches named \`bundle/*\`.\n\n` +
              `Current source branch: \`${head}\`\n\n` +
              `Merge your developments into a bundle branch instead of directly merging to master or 1.x.`;

            // Find an existing marker comment (to update instead of spamming)
            const { data: comments } = await github.rest.issues.listComments({
              owner,
              repo,
              issue_number,
              per_page: 100,
            });

            const existing = comments.find(c => c.body && c.body.includes(marker));

            if (existing) {
              await github.rest.issues.updateComment({
                owner,
                repo,
                comment_id: existing.id,
                body,
              });
            } else {
              await github.rest.issues.createComment({
                owner,
                repo,
                issue_number,
                body,
              });
            }

      - name: Fail (blocked)
        if: ${{ steps.validate.outputs.allowed == 'false' }}
        env:
          HEAD_REF: ${{ github.head_ref }}
        run: |
          echo "::error::You can only merge to master and 1.x from a bundle/* branch. Got '$HEAD_REF'."
          exit 1

      - name: Allowed
        if: ${{ steps.validate.outputs.allowed == 'true' }}
        env:
          HEAD_REF: ${{ github.head_ref }}
          BASE_REF: ${{ github.base_ref }}
        run: |
          echo "OK: '$HEAD_REF' can merge into '$BASE_REF'"
