#!/bin/bash
#
# Azure Resource Provider Registration Script
# Registers all required resource providers for The Order
#

set -e

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

# 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
)

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Azure Resource Provider Registration${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}"
    exit 1
fi

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

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

# Check current registration status
echo -e "${YELLOW}Checking current registration status...${NC}"
echo ""

UNREGISTERED=()
ALREADY_REGISTERED=()
REGISTERING=()

for provider in "${REQUIRED_PROVIDERS[@]}"; do
    STATUS=$(az provider show --namespace "${provider}" --query "registrationState" -o tsv 2>/dev/null || echo "NotRegistered")
    
    if [ "${STATUS}" == "Registered" ]; then
        echo -e "${GREEN}✓ ${provider} - Already Registered${NC}"
        ALREADY_REGISTERED+=("${provider}")
    elif [ "${STATUS}" == "Registering" ]; then
        echo -e "${YELLOW}⏳ ${provider} - Currently Registering${NC}"
        REGISTERING+=("${provider}")
    else
        echo -e "${RED}✗ ${provider} - Not Registered${NC}"
        UNREGISTERED+=("${provider}")
    fi
done

echo ""

# Register unregistered providers
if [ ${#UNREGISTERED[@]} -gt 0 ]; then
    echo -e "${YELLOW}Registering ${#UNREGISTERED[@]} unregistered provider(s)...${NC}"
    echo ""
    
    for provider in "${UNREGISTERED[@]}"; do
        echo -n "Registering ${provider}... "
        az provider register --namespace "${provider}" --wait
        echo -e "${GREEN}✓ Registered${NC}"
    done
    echo ""
fi

# Wait for providers that are currently registering
if [ ${#REGISTERING[@]} -gt 0 ]; then
    echo -e "${YELLOW}Waiting for ${#REGISTERING[@]} provider(s) to finish registering...${NC}"
    echo ""
    
    for provider in "${REGISTERING[@]}"; do
        echo -n "Waiting for ${provider}... "
        az provider register --namespace "${provider}" --wait
        echo -e "${GREEN}✓ Registered${NC}"
    done
    echo ""
fi

# Final status check
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Final Registration Status${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

ALL_REGISTERED=true
for provider in "${REQUIRED_PROVIDERS[@]}"; do
    STATUS=$(az provider show --namespace "${provider}" --query "registrationState" -o tsv)
    
    if [ "${STATUS}" == "Registered" ]; then
        echo -e "${GREEN}✓ ${provider}${NC}"
    else
        echo -e "${RED}✗ ${provider} - Status: ${STATUS}${NC}"
        ALL_REGISTERED=false
    fi
done

echo ""

if [ "${ALL_REGISTERED}" = true ]; then
    echo -e "${GREEN}✓ All required resource providers are registered!${NC}"
    exit 0
else
    echo -e "${YELLOW}⚠ Some providers are not yet registered. Please wait and run this script again.${NC}"
    exit 1
fi

