#!/bin/bash
# =====================================
# GitHub Branch Protection Setup Script
# =====================================
# This script configures branch protection rules for main, staging, and develop branches
# Requires: GitHub CLI (gh) installed and authenticated
#
# Usage: ./scripts/setup-branch-protection.sh

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}GitHub Branch Protection Setup${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if gh CLI is installed
if ! command -v gh &> /dev/null; then
    echo -e "${RED}❌ GitHub CLI (gh) is not installed${NC}"
    echo -e "${YELLOW}Install with: brew install gh${NC}"
    exit 1
fi

# Check if authenticated
if ! gh auth status &> /dev/null; then
    echo -e "${RED}❌ Not authenticated with GitHub${NC}"
    echo -e "${YELLOW}Run: gh auth login${NC}"
    exit 1
fi

# Get repository info
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
echo -e "${GREEN}✅ Authenticated and working with: $REPO${NC}"
echo ""

# =====================================
# Function: Create Branch Protection
# =====================================
create_branch_protection() {
    local branch=$1
    local required_approvals=$2
    local strict_status_checks=$3
    shift 3
    local required_checks=("$@")

    echo -e "${BLUE}Configuring protection for: ${branch}${NC}"

    # Build status checks array
    local checks_json="["
    for check in "${required_checks[@]}"; do
        checks_json+="\"$check\","
    done
    checks_json="${checks_json%,}]"

    # Create protection rule
    gh api \
      --method PUT \
      -H "Accept: application/vnd.github+json" \
      "/repos/${REPO}/branches/${branch}/protection" \
      -f required_status_checks[strict]="${strict_status_checks}" \
      -F required_status_checks[contexts]="${checks_json}" \
      -f required_pull_request_reviews[required_approving_review_count]="${required_approvals}" \
      -f required_pull_request_reviews[dismiss_stale_reviews]=true \
      -f required_pull_request_reviews[require_code_owner_reviews]=true \
      -f required_linear_history=true \
      -f allow_force_pushes=false \
      -f allow_deletions=false \
      -f required_conversation_resolution=true \
      > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}  ✅ ${branch} protection configured${NC}"
    else
        echo -e "${RED}  ❌ Failed to configure ${branch} protection${NC}"
        echo -e "${YELLOW}  Note: Branch may not exist yet. Create it first.${NC}"
    fi
}

# =====================================
# Main Branch (Production)
# =====================================
echo -e "${YELLOW}Configuring main branch (production)...${NC}"
create_branch_protection "main" 2 true \
    "unit-tests" \
    "e2e-tests" \
    "security-scan" \
    "build" \
    "typescript-check" \
    "lint"

# =====================================
# Staging Branch (Pre-Production)
# =====================================
echo -e "${YELLOW}Configuring staging branch (pre-production)...${NC}"
create_branch_protection "staging" 1 true \
    "unit-tests" \
    "e2e-tests" \
    "security-scan" \
    "build"

# =====================================
# Develop Branch (Development)
# =====================================
echo -e "${YELLOW}Configuring develop branch (development)...${NC}"
create_branch_protection "develop" 1 false \
    "unit-tests" \
    "lint" \
    "typescript-check"

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Branch Protection Setup Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}Next Steps:${NC}"
echo -e "1. Verify branch protection in GitHub UI"
echo -e "2. Create CODEOWNERS file if not exists"
echo -e "3. Test PR creation to protected branches"
echo ""
echo -e "${YELLOW}View settings:${NC}"
echo -e "  gh repo view --web"
echo -e "  Then navigate to: Settings > Branches"
echo ""
