#!/usr/bin/env bash

# Grant Key Vault permissions in parallel for faster execution
# Handles both access policies and RBAC-enabled vaults

set -e

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

# Your AAD object ID
OBJECT_ID="5c40d456-49d2-4f2a-b35c-66255ca33b04"

# Email for logging
USER_EMAIL="admin@absoluterealms.org"

# Subscription ID
SUBSCRIPTION_ID="fc08d829-4f14-413d-ab27-ce024425db0b"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     GRANTING KEY VAULT PERMISSIONS - PARALLEL EXECUTION         ║"
echo "╚════════════════════════════════════════════════════════════════╝"

echo "User: $USER_EMAIL"
echo "Object ID: $OBJECT_ID"
echo "Subscription: $SUBSCRIPTION_ID"

# Set subscription
az account set --subscription "$SUBSCRIPTION_ID" > /dev/null 2>&1

echo "Processing subscription: $SUBSCRIPTION_ID"

# Get all Key Vault names
VAULTS=$(az keyvault list --query "[].name" -o tsv 2>/dev/null)

if [ -z "$VAULTS" ]; then
    echo "❌ No Key Vaults found"
    exit 1
fi

TOTAL=$(echo "$VAULTS" | wc -l)
echo "Total Key Vaults: $TOTAL"

# Function to grant permissions for a single vault
grant_permissions() {
    local kv_name="$1"
    local object_id="$2"
    local subscription_id="$3"
    
    # Get resource group
    local kv_rg=$(az keyvault show --name "$kv_name" --query "resourceGroup" -o tsv 2>/dev/null)
    
    if [ -z "$kv_rg" ]; then
        echo "❌ $kv_name: Could not get resource group"
        return 1
    fi
    
    # Check if RBAC-enabled
    local is_rbac=$(az keyvault show --name "$kv_name" --query "properties.enableRbacAuthorization" -o tsv 2>/dev/null)
    
    if [ "$is_rbac" = "true" ]; then
        # Use RBAC role assignment
        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 2>&1; then
            echo "✅ $kv_name: RBAC role assigned"
            return 0
        else
            echo "❌ $kv_name: Failed to assign RBAC role"
            return 1
        fi
    else
        # Use access 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 2>&1; then
            echo "✅ $kv_name: Access policy updated"
            return 0
        else
            echo "❌ $kv_name: Failed to update access policy"
            return 1
        fi
    fi
}

export -f grant_permissions
export OBJECT_ID
export SUBSCRIPTION_ID

echo "Granting permissions (parallel execution)..."

# Process in parallel (max 5 concurrent)
SUCCESS_COUNT=0
FAILED_COUNT=0

while IFS= read -r kv_name; do
    if grant_permissions "$kv_name" "$OBJECT_ID" "$SUBSCRIPTION_ID"; then
        ((SUCCESS_COUNT++))
    else
        ((FAILED_COUNT++))
    fi
done < <(echo "$VAULTS" | xargs -P 5 -I {} bash -c 'grant_permissions "$@"' _ {})

echo "======================================================================"
echo "📊 SUMMARY"
echo "======================================================================"
echo "Total Key Vaults processed: $TOTAL"
echo "✅ Success: $SUCCESS_COUNT"
echo "❌ Failed: $FAILED_COUNT"

if [ $FAILED_COUNT -eq 0 ]; then
    echo "✅ All permissions granted successfully"
    exit 0
else
    echo "⚠️  Some permissions failed - check errors above"
    exit 1
fi

