#!/bin/bash
# Azure Resources Testing Script
# Tests Azure resources via Azure CLI

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

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

echo "=========================================="
echo "Azure Resources Testing"
echo "=========================================="
echo ""

# Check Azure CLI
if ! command -v az > /dev/null 2>&1; then
    echo -e "${RED}✗${NC} Azure CLI not installed"
    exit 1
fi

# Check Azure login
if ! az account show > /dev/null 2>&1; then
    echo -e "${RED}✗${NC} Not logged in to Azure. Run: az login"
    exit 1
fi

echo -e "${GREEN}✓${NC} Azure CLI authenticated"
echo ""

cd "$PHASE1_DIR"

# Test Resource Groups
echo "Testing Resource Groups..."
RGS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | .value.resource_group' || echo "")
RGS="$RGS $(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value // {} | .resource_group // empty' || echo "")"

RG_COUNT=0
RG_FOUND=0
for rg in $RGS; do
    if [ -n "$rg" ] && [ "$rg" != "null" ]; then
        ((RG_COUNT++))
        if az group show --name "$rg" > /dev/null 2>&1; then
            echo -e "  ${GREEN}✓${NC} $rg"
            ((RG_FOUND++))
        else
            echo -e "  ${RED}✗${NC} $rg (not found)"
        fi
    fi
done

if [ $RG_FOUND -ge 6 ]; then
    echo -e "${GREEN}✓${NC} Resource Groups: $RG_FOUND/$RG_COUNT found"
else
    echo -e "${YELLOW}⊘${NC} Resource Groups: $RG_FOUND/$RG_COUNT found"
fi

# Test Virtual Machines
echo ""
echo "Testing Virtual Machines..."
VMS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | "\(.value.resource_group):\(.value.vm_names[0])"' || echo "")

VM_COUNT=0
VM_RUNNING=0
VM_STOPPED=0
VM_NOT_FOUND=0

while IFS=: read -r rg vm_name; do
    if [ -n "$vm_name" ] && [ "$vm_name" != "null" ] && [ -n "$rg" ]; then
        ((VM_COUNT++))
        VM_STATE=$(az vm show --resource-group "$rg" --name "$vm_name" --show-details --query "powerState" -o tsv 2>/dev/null || echo "NotFound")
        case "$VM_STATE" in
            "VM running")
                echo -e "  ${GREEN}✓${NC} $vm_name ($rg): Running"
                ((VM_RUNNING++))
                ;;
            "VM deallocated"|"VM stopped")
                echo -e "  ${YELLOW}⊘${NC} $vm_name ($rg): Stopped"
                ((VM_STOPPED++))
                ;;
            *)
                echo -e "  ${RED}✗${NC} $vm_name ($rg): Not found"
                ((VM_NOT_FOUND++))
                ;;
        esac
    fi
done <<< "$VMS"

# Test Nginx proxy VM
NGINX_RG=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value // {} | .resource_group // empty' || echo "")
if [ -n "$NGINX_RG" ] && [ "$NGINX_RG" != "null" ]; then
    NGINX_VM="az-p-wst-proxy-nginx"
    NGINX_STATE=$(az vm show --resource-group "$NGINX_RG" --name "$NGINX_VM" --show-details --query "powerState" -o tsv 2>/dev/null || echo "NotFound")
    case "$NGINX_STATE" in
        "VM running")
            echo -e "  ${GREEN}✓${NC} $NGINX_VM ($NGINX_RG): Running"
            ((VM_RUNNING++))
            ;;
        "VM deallocated"|"VM stopped")
            echo -e "  ${YELLOW}⊘${NC} $NGINX_VM ($NGINX_RG): Stopped"
            ((VM_STOPPED++))
            ;;
        *)
            echo -e "  ${RED}✗${NC} $NGINX_VM ($NGINX_RG): Not found"
            ((VM_NOT_FOUND++))
            ;;
    esac
    ((VM_COUNT++))
fi

echo ""
echo "VM Status Summary:"
echo "  Running: $VM_RUNNING"
echo "  Stopped: $VM_STOPPED"
echo "  Not Found: $VM_NOT_FOUND"

# Test Storage Accounts
echo ""
echo "Testing Storage Accounts..."
STORAGE_ACCOUNTS=$(terraform output -json 2>/dev/null | jq -r '.storage_accounts.value.boot_diagnostics | to_entries[] | "\(.value.name)"' || echo "")
STORAGE_COUNT=0
STORAGE_FOUND=0

for sa in $STORAGE_ACCOUNTS; do
    if [ -n "$sa" ] && [ "$sa" != "null" ]; then
        ((STORAGE_COUNT++))
        if az storage account show --name "$sa" > /dev/null 2>&1; then
            echo -e "  ${GREEN}✓${NC} $sa"
            ((STORAGE_FOUND++))
        else
            echo -e "  ${RED}✗${NC} $sa (not found)"
        fi
    fi
done

if [ $STORAGE_FOUND -eq $STORAGE_COUNT ] && [ $STORAGE_COUNT -gt 0 ]; then
    echo -e "${GREEN}✓${NC} Storage Accounts: $STORAGE_FOUND/$STORAGE_COUNT found"
else
    echo -e "${YELLOW}⊘${NC} Storage Accounts: $STORAGE_FOUND/$STORAGE_COUNT found"
fi

# Test Key Vault
echo ""
echo "Testing Key Vault..."
KEY_VAULT=$(terraform output -json 2>/dev/null | jq -r '.key_vault_name.value // empty' || echo "")
if [ -n "$KEY_VAULT" ] && [ "$KEY_VAULT" != "null" ]; then
    if az keyvault show --name "$KEY_VAULT" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Key Vault: $KEY_VAULT (accessible)"
        
        # Test access policies
        POLICIES=$(az keyvault show --name "$KEY_VAULT" --query "properties.accessPolicies" -o json 2>/dev/null || echo "[]")
        POLICY_COUNT=$(echo "$POLICIES" | jq -r 'length' || echo "0")
        echo -e "  ${BLUE}ℹ${NC} Access policies: $POLICY_COUNT"
    else
        echo -e "${RED}✗${NC} Key Vault: $KEY_VAULT (not accessible)"
    fi
else
    echo -e "${RED}✗${NC} Key Vault not found"
fi

# Test Log Analytics Workspaces
echo ""
echo "Testing Log Analytics Workspaces..."
MONITORING=$(terraform output -json 2>/dev/null | jq -r '.monitoring.value | to_entries[] | .value.log_analytics_workspace_name' || echo "")
MONITORING_COUNT=0
MONITORING_FOUND=0

for ws in $MONITORING; do
    if [ -n "$ws" ] && [ "$ws" != "null" ]; then
        ((MONITORING_COUNT++))
        WS_ID=$(az monitor log-analytics workspace show --workspace-name "$ws" --query "id" -o tsv 2>/dev/null || echo "")
        if [ -n "$WS_ID" ]; then
            echo -e "  ${GREEN}✓${NC} $ws"
            ((MONITORING_FOUND++))
        else
            echo -e "  ${RED}✗${NC} $ws (not found)"
        fi
    fi
done

if [ $MONITORING_FOUND -eq $MONITORING_COUNT ] && [ $MONITORING_COUNT -gt 0 ]; then
    echo -e "${GREEN}✓${NC} Log Analytics Workspaces: $MONITORING_FOUND/$MONITORING_COUNT found"
else
    echo -e "${YELLOW}⊘${NC} Log Analytics Workspaces: $MONITORING_FOUND/$MONITORING_COUNT found"
fi

# Test Recovery Services Vaults
echo ""
echo "Testing Recovery Services Vaults..."
BACKUPS=$(terraform output -json 2>/dev/null | jq -r '.backups.value | to_entries[] | .value.recovery_services_vault_name' || echo "")
BACKUP_COUNT=0
BACKUP_FOUND=0

for vault in $BACKUPS; do
    if [ -n "$vault" ] && [ "$vault" != "null" ]; then
        ((BACKUP_COUNT++))
        VAULT_RG=$(az backup vault list --query "[?name=='$vault'].resourceGroup" -o tsv 2>/dev/null | head -1 || echo "")
        if [ -n "$VAULT_RG" ]; then
            echo -e "  ${GREEN}✓${NC} $vault ($VAULT_RG)"
            ((BACKUP_FOUND++))
        else
            echo -e "  ${RED}✗${NC} $vault (not found)"
        fi
    fi
done

if [ $BACKUP_FOUND -eq $BACKUP_COUNT ] && [ $BACKUP_COUNT -gt 0 ]; then
    echo -e "${GREEN}✓${NC} Recovery Services Vaults: $BACKUP_FOUND/$BACKUP_COUNT found"
else
    echo -e "${YELLOW}⊘${NC} Recovery Services Vaults: $BACKUP_FOUND/$BACKUP_COUNT found"
fi

echo ""
echo "=========================================="
echo "Azure Resources Test Complete"
echo "=========================================="

