#!/bin/bash
#
# Azure Setup Script for The Order
# This script sets up Azure prerequisites including:
# - Listing available regions (excluding US)
# - Checking and registering required resource providers
# - Checking quotas for all regions
# - Setting default region to West Europe
#

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

# Default region
DEFAULT_REGION="westeurope"

# Required Resource Providers
REQUIRED_PROVIDERS=(
    "Microsoft.ContainerService"           # AKS
    "Microsoft.KeyVault"                   # Key Vault
    "Microsoft.Storage"                    # Storage Accounts
    "Microsoft.Network"                   # Networking
    "Microsoft.Compute"                    # Compute resources
    "Microsoft.DBforPostgreSQL"            # PostgreSQL
    "Microsoft.ContainerRegistry"         # ACR
    "Microsoft.ManagedIdentity"            # Managed Identities
    "Microsoft.Insights"                  # Application Insights, Monitor
    "Microsoft.Logic"                      # Logic Apps
    "Microsoft.OperationalInsights"        # Log Analytics
    "Microsoft.Authorization"              # RBAC
    "Microsoft.Resources"                 # Resource Manager
)

# Preview Features (if needed)
PREVIEW_FEATURES=(
    # Add preview features here if needed
    # Example: "Microsoft.ContainerService/EnableWorkloadIdentityPreview"
)

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Azure Setup for The Order${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if Azure CLI is installed
if ! command -v az &> /dev/null; then
    echo -e "${RED}Error: Azure CLI is not installed.${NC}"
    echo "Please install it from: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
    exit 1
fi

# Check if logged in
echo -e "${YELLOW}Checking Azure CLI login status...${NC}"
if ! az account show &> /dev/null; then
    echo -e "${YELLOW}Not logged in. Please log in...${NC}"
    az login
fi

# Get current subscription
SUBSCRIPTION_ID=$(az account show --query id -o tsv)
SUBSCRIPTION_NAME=$(az account show --query name -o tsv)
echo -e "${GREEN}Current Subscription: ${SUBSCRIPTION_NAME} (${SUBSCRIPTION_ID})${NC}"
echo ""

# Set default region
echo -e "${BLUE}Setting default region to: ${DEFAULT_REGION}${NC}"
export AZURE_DEFAULT_REGION=${DEFAULT_REGION}
echo ""

# ============================================
# 1. List All Azure Commercial Regions (Excluding US)
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}1. Available Azure Commercial Regions${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Get all locations and filter out US regions
echo -e "${YELLOW}Fetching available regions (excluding US)...${NC}"
az account list-locations \
    --query "[?metadata.regionType=='Physical' && !contains(name, 'us')].{Name:name, DisplayName:displayName, RegionalDisplayName:regionalDisplayName}" \
    -o table

echo ""
echo -e "${YELLOW}Recommended regions for The Order:${NC}"
echo "  - westeurope (Primary - Default)"
echo "  - northeurope (Secondary)"
echo "  - uksouth (UK)"
echo "  - switzerlandnorth (Switzerland)"
echo "  - norwayeast (Norway)"
echo ""

# Save regions to file
REGIONS_FILE="azure-regions.txt"
az account list-locations \
    --query "[?metadata.regionType=='Physical' && !contains(name, 'us')].name" \
    -o tsv > "${REGIONS_FILE}"
echo -e "${GREEN}Regions list saved to: ${REGIONS_FILE}${NC}"
echo ""

# ============================================
# 2. List Required Resource Providers
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}2. Required Resource Providers${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

echo -e "${YELLOW}Required Resource Providers:${NC}"
for provider in "${REQUIRED_PROVIDERS[@]}"; do
    echo "  - ${provider}"
done
echo ""

# ============================================
# 3. Check and Register Resource Providers
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}3. Checking Resource Provider Registration${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

UNREGISTERED_PROVIDERS=()

for provider in "${REQUIRED_PROVIDERS[@]}"; do
    echo -n "Checking ${provider}... "
    STATUS=$(az provider show --namespace "${provider}" --query "registrationState" -o tsv 2>/dev/null || echo "NotRegistered")
    
    if [ "${STATUS}" == "Registered" ]; then
        echo -e "${GREEN}✓ Registered${NC}"
    else
        echo -e "${YELLOW}✗ Not Registered${NC}"
        UNREGISTERED_PROVIDERS+=("${provider}")
    fi
done
echo ""

# Register unregistered providers
if [ ${#UNREGISTERED_PROVIDERS[@]} -gt 0 ]; then
    echo -e "${YELLOW}Registering unregistered providers...${NC}"
    for provider in "${UNREGISTERED_PROVIDERS[@]}"; do
        echo -n "Registering ${provider}... "
        az provider register --namespace "${provider}" --wait
        echo -e "${GREEN}✓ Registered${NC}"
    done
    echo ""
else
    echo -e "${GREEN}All required providers are already registered!${NC}"
    echo ""
fi

# ============================================
# 4. Check Preview Features
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}4. Preview Features${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

if [ ${#PREVIEW_FEATURES[@]} -gt 0 ]; then
    echo -e "${YELLOW}Required Preview Features:${NC}"
    for feature in "${PREVIEW_FEATURES[@]}"; do
        echo "  - ${feature}"
    done
    echo ""
    
    echo -e "${YELLOW}Note: Preview features may need to be enabled manually in Azure Portal${NC}"
    echo ""
else
    echo -e "${GREEN}No preview features required.${NC}"
    echo ""
fi

# ============================================
# 5. Check Quotas for All Regions
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}5. Checking Quotas for All Regions${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Read regions from file
REGIONS=$(cat "${REGIONS_FILE}")

# Quota types to check
QUOTA_TYPES=(
    "cores"           # VM cores
    "virtualMachines" # VM instances
)

# Primary regions to check in detail
PRIMARY_REGIONS=("westeurope" "northeurope" "uksouth")

echo -e "${YELLOW}Checking quotas for primary regions...${NC}"
echo ""

QUOTA_FILE="azure-quotas.txt"
> "${QUOTA_FILE}"  # Clear file

for region in "${PRIMARY_REGIONS[@]}"; do
    echo -e "${BLUE}Region: ${region}${NC}"
    echo "----------------------------------------"
    
    # Get VM family quotas
    echo "VM Family Quotas:"
    az vm list-usage \
        --location "${region}" \
        --query "[].{Name:name.value, CurrentValue:currentValue, Limit:limit}" \
        -o table 2>/dev/null || echo "  Unable to fetch VM quotas"
    
    echo "" >> "${QUOTA_FILE}"
    echo "Region: ${region}" >> "${QUOTA_FILE}"
    echo "----------------------------------------" >> "${QUOTA_FILE}"
    az vm list-usage --location "${region}" -o table >> "${QUOTA_FILE}" 2>/dev/null || true
    echo "" >> "${QUOTA_FILE}"
    
    # Get storage account quota
    echo "Storage Account Quota:"
    STORAGE_QUOTA=$(az storage account show-usage \
        --location "${region}" \
        --query "{CurrentValue:currentValue, Limit:limit}" \
        -o json 2>/dev/null || echo '{"CurrentValue": "N/A", "Limit": "N/A"}')
    echo "${STORAGE_QUOTA}" | jq '.' 2>/dev/null || echo "${STORAGE_QUOTA}"
    
    echo ""
done

echo -e "${GREEN}Detailed quota information saved to: ${QUOTA_FILE}${NC}"
echo ""

# ============================================
# 6. Summary
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Setup Summary${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "${GREEN}✓ Default region set to: ${DEFAULT_REGION}${NC}"
echo -e "${GREEN}✓ Available regions listed (excluding US)${NC}"
echo -e "${GREEN}✓ Resource providers checked and registered${NC}"
echo -e "${GREEN}✓ Quotas checked for primary regions${NC}"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "  1. Review quota limits in ${QUOTA_FILE}"
echo "  2. Update Terraform variables with region: ${DEFAULT_REGION}"
echo "  3. Proceed with infrastructure deployment"
echo ""

