#!/usr/bin/env bash

# Fix Resource Groups and Key Vaults
# REFACTORED - Uses common libraries
# 1. Create resource groups if missing (6 per region × 37 regions = 222 total)
# 2. Create Key Vaults with correct naming (dashes) if missing
# 3. Ensure proper permissions on all Key Vaults
# Note: Azure Key Vaults cannot be renamed - new vaults created with correct names

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"

# Initialize
SUBSCRIPTION_ID="$(get_subscription_id)"
OBJECT_ID="${OBJECT_ID:-5c40d456-49d2-4f2a-b35c-66255ca33b04}"

ensure_azure_cli || exit 1
set_subscription "$SUBSCRIPTION_ID" || true

log_section "FIXING RESOURCE GROUPS AND KEY VAULTS"

# Get all regions from library
region_map=($(get_all_regions))

log_subsection "PHASE 1: CREATE MISSING RESOURCE GROUPS"

rg_created=0
rg_existing=0

for region_info in "${region_map[@]}"; do
    region_name="${region_info%%:*}"
    region_code="${region_info#*:}"
    
    # Resource groups (6 per region)
    rgs=(
        "az-p-${region_code}-rg-net-001"
        "az-p-${region_code}-rg-comp-001"
        "az-p-${region_code}-rg-stor-001"
        "az-p-${region_code}-rg-sec-001"
        "az-p-${region_code}-rg-mon-001"
        "az-p-${region_code}-rg-id-001"
    )
    
    for rg_name in "${rgs[@]}"; do
        # Check if resource group exists
        if az group show --name "$rg_name" &> /dev/null; then
            ((rg_existing++))
            if [ "$rg_created" -eq 0 ] && [ "$rg_existing" -le 6 ]; then
                log_success "Resource groups exist for ${region_name}..."
            fi
        else
            # Create resource group
            if az group create \
                --name "$rg_name" \
                --location "$region_name" \
                --tags Environment=production Project="DeFi Oracle Meta Mainnet" ChainID=138 ManagedBy=Terraform \
                &> /dev/null; then
                log_success "Created: $rg_name"
                ((rg_created++))
            else
                log_failure "Failed: $rg_name"
            fi
        fi
    done
done

echo ""
log_info "Resource Groups: Created=$rg_created, Existing=$rg_existing, Total=$((rg_created + rg_existing))"
echo ""

log_subsection "PHASE 2: CREATE KEY VAULTS WITH CORRECT NAMING (DASHES)"

kv_created=0
kv_existing=0
kv_legacy=0

for region_info in "${region_map[@]}"; do
    region_name="${region_info%%:*}"
    region_code="${region_info#*:}"
    
    expected_name="az-p-${region_code}-kv-secrets-001"
    legacy_name="azp${region_code}kvsecrets001"
    rg_name="az-p-${region_code}-rg-sec-001"
    
    # Check if Key Vault exists with expected name (dashes)
    if az keyvault show --name "$expected_name" &> /dev/null; then
        ((kv_existing++))
        if [ "$kv_created" -eq 0 ]; then
            log_success "Key Vaults with correct naming exist..."
        fi
        continue
    fi
    
    # Check if legacy name exists (no dashes)
    if az keyvault show --name "$legacy_name" &> /dev/null; then
        log_warn "Legacy vault found: $legacy_name"
        log_info "  → Creating new vault with correct name: $expected_name"
        ((kv_legacy++))
    else
        log_warn "Missing: $expected_name"
    fi
    
    # Ensure resource group exists first
    if ! az group show --name "$rg_name" &> /dev/null; then
        az group create --name "$rg_name" --location "$region_name" \
            --tags Environment=production Project="DeFi Oracle Meta Mainnet" ChainID=138 ManagedBy=Terraform \
            &> /dev/null
    fi
    
    # Create new Key Vault with correct name
    if az keyvault create \
        --name "$expected_name" \
        --resource-group "$rg_name" \
        --location "$region_name" \
        --sku standard \
        --soft-delete-retention-days 7 \
        &> /dev/null; then
        echo -e "  ${GREEN}✅ Created: $expected_name${NC}"
        ((kv_created++))
    else
        echo -e "  ${RED}❌ Failed: $expected_name${NC}"
    fi
done

echo ""
log_info "Key Vaults: Created=$kv_created, Existing=$kv_existing, Legacy=$kv_legacy"
echo ""

if [ "$kv_legacy" -gt 0 ]; then
    log_warn "Note: Legacy Key Vaults cannot be renamed. New vaults created with correct naming."
    log_warn "Secrets can be migrated manually from legacy vaults."
    echo ""
fi

log_subsection "PHASE 3: ENSURE PERMISSIONS"

permissions_granted=0
permissions_failed=0

for region_info in "${region_map[@]}"; do
    region_code="${region_info#*:}"
    
    kv_name="az-p-${region_code}-kv-secrets-001"
    
    # Only grant permissions to vaults with correct naming
    if az keyvault show --name "$kv_name" &> /dev/null; then
        kv_rg=$(az keyvault show --name "$kv_name" --query "resourceGroup" -o tsv 2>/dev/null)
        
        # Check if RBAC or access policy
        is_rbac=$(az keyvault show --name "$kv_name" --query "properties.enableRbacAuthorization" -o tsv 2>/dev/null)
        
        if [ "$is_rbac" = "true" ]; then
            # RBAC - check if role already assigned
            role_exists=$(az role assignment list \
                --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$kv_rg/providers/Microsoft.KeyVault/vaults/$kv_name" \
                --assignee "$OBJECT_ID" \
                --role "Key Vault Secrets Officer" \
                --query "[].{principalName:principalName}" \
                -o tsv 2>/dev/null | wc -l)
            
            if [ "$role_exists" -gt 0 ]; then
                ((permissions_granted++))
                if [ "$permissions_granted" -le 5 ]; then
                    log_success "$kv_name: RBAC role assigned"
                fi
            else
                if az role assignment create \
                    --role "Key Vault Secrets Officer" \
                    --assignee "$OBJECT_ID" \
                    --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$kv_rg/providers/Microsoft.KeyVault/vaults/$kv_name" \
                    &> /dev/null; then
                    ((permissions_granted++))
                    log_success "$kv_name: RBAC role assigned"
                else
                    ((permissions_failed++))
                    log_failure "$kv_name: Failed RBAC assignment"
                fi
            fi
        else
            # Access Policy - update policy
            if az keyvault set-policy \
                --name "$kv_name" \
                --object-id "$OBJECT_ID" \
                --secret-permissions get list set delete backup restore recover purge \
                &> /dev/null; then
                ((permissions_granted++))
                if [ "$permissions_granted" -le 5 ]; then
                    log_success "$kv_name: Access policy updated"
                fi
            else
                ((permissions_failed++))
                log_failure "$kv_name: Failed policy update"
            fi
        fi
    fi
done

echo ""
log_section "SUMMARY"

log_info "Resource Groups:"
echo "  Created: $rg_created"
echo "  Existing: $rg_existing"
echo "  Total: $((rg_created + rg_existing))"
echo ""

log_info "Key Vaults:"
echo "  Created (with dashes): $kv_created"
echo "  Existing (with dashes): $kv_existing"
echo "  Legacy (no dashes): $kv_legacy"
echo ""

log_info "Permissions:"
echo "  Granted: $permissions_granted"
echo "  Failed: $permissions_failed"
echo ""

if [ "$kv_legacy" -gt 0 ]; then
    log_warn "ACTION: Legacy Key Vaults found. New vaults created with correct naming."
    log_info "  Migrate secrets from legacy vaults to new vaults if needed."
    echo ""
fi

if [ "$permissions_failed" -eq 0 ] && [ "$kv_created" -eq 0 ]; then
    log_success "All resource groups and Key Vaults configured correctly"
    exit 0
else
    log_success "Resource groups and Key Vaults configured"
    exit 0
fi
