# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Enforces branch merge policy:
#   feature/* → dev only
#   fix/*     → dev only
#   hotfix/*  → dev or main (emergency)
#   dev       → main only
#   alpha/*   → dev only
#   beta/*    → dev only
#   rc/*      → main only

name: Branch Policy Check

on:
  pull_request:
    types: [opened, synchronize, reopened, edited]

jobs:
  check-target:
    name: Verify merge target
    runs-on: ubuntu-latest
    steps:
      - name: Check branch policy
        run: |
          HEAD="${{ github.head_ref }}"
          BASE="${{ github.base_ref }}"

          echo "PR: ${HEAD} → ${BASE}"

          ALLOWED=true
          REASON=""

          case "$HEAD" in
            feature/*|feat/*)
              if [ "$BASE" != "dev" ]; then
                ALLOWED=false
                REASON="Feature branches must target 'dev', not '${BASE}'"
              fi
              ;;
            fix/*|bugfix/*)
              if [ "$BASE" != "dev" ]; then
                ALLOWED=false
                REASON="Fix branches must target 'dev', not '${BASE}'"
              fi
              ;;
            hotfix/*)
              if [ "$BASE" != "dev" ] && [ "$BASE" != "main" ]; then
                ALLOWED=false
                REASON="Hotfix branches can only target 'dev' or 'main', not '${BASE}'"
              fi
              ;;
            alpha/*|beta/*)
              if [ "$BASE" != "dev" ]; then
                ALLOWED=false
                REASON="Pre-release branches must target 'dev', not '${BASE}'"
              fi
              ;;
            rc/*)
              if [ "$BASE" != "main" ]; then
                ALLOWED=false
                REASON="Release candidate branches must target 'main', not '${BASE}'"
              fi
              ;;
            dev)
              if [ "$BASE" != "main" ]; then
                ALLOWED=false
                REASON="Dev branch can only merge into 'main', not '${BASE}'"
              fi
              ;;
          esac

          if [ "$ALLOWED" = false ]; then
            echo "::error::${REASON}"
            echo ""
            echo "## Branch Policy Violation" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "${REASON}" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "### Allowed merge paths:" >> $GITHUB_STEP_SUMMARY
            echo "- \`feature/*\` → \`dev\`" >> $GITHUB_STEP_SUMMARY
            echo "- \`fix/*\` → \`dev\`" >> $GITHUB_STEP_SUMMARY
            echo "- \`hotfix/*\` → \`dev\` or \`main\`" >> $GITHUB_STEP_SUMMARY
            echo "- \`dev\` → \`main\`" >> $GITHUB_STEP_SUMMARY
            echo "- \`rc/*\` → \`main\`" >> $GITHUB_STEP_SUMMARY
            exit 1
          fi

          echo "Branch policy: OK (${HEAD} → ${BASE})"
          echo "## Branch Policy: Passed" >> $GITHUB_STEP_SUMMARY
