#!/usr/bin/env bash
# Fix AKS Deployment Issues

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "==================================================================="
echo "  FIXING AKS DEPLOYMENT CONFIGURATION"
echo "==================================================================="

# Check if cluster exists in old subscription
OLD_SUB="6d3c4263-bba9-497c-8843-eae6c4e87192"
NEW_SUB="fc08d829-4f14-413d-ab27-ce024425db0b"
RG_NAME="az-p-we-rg-comp-001"
CLUSTER_NAME="az-p-we-aks-main"

log_info "Checking for existing cluster..."

# Try old subscription
az account set --subscription "$OLD_SUB" 2>/dev/null || true
if az aks show --resource-group "$RG_NAME" --name "$CLUSTER_NAME" &> /dev/null 2>&1; then
    log_warn "⚠️  Cluster exists in old subscription: $OLD_SUB"
    echo "   Options:"
    echo "   1. Import cluster to new subscription (complex)"
    echo "   2. Create new cluster in new subscription (recommended)"
    echo "   3. Use existing cluster from old subscription"
    log_warn "⚠️  For now, we'll create a new cluster in the new subscription"
fi

# Switch to new subscription
az account set --subscription "$NEW_SUB"
log_success "✅ Using subscription: $NEW_SUB"

# Check if cluster exists in new subscription
if az aks show --resource-group "$RG_NAME" --name "$CLUSTER_NAME" &> /dev/null 2>&1; then
    log_success "✅ Cluster exists in new subscription"
else
    log_warn "⚠️  Cluster does not exist in new subscription"
    echo "   Will be created by Terraform"
fi

log_info "Checking Terraform state..."

cd terraform

# Check if cluster is in state
if terraform state list 2>/dev/null | grep -q "module.aks.azurerm_kubernetes_cluster.main"; then
    log_warn "⚠️  Cluster found in Terraform state"
    echo "   May need to remove from state if it's in wrong subscription"
    echo "   Run: terraform state rm module.aks.azurerm_kubernetes_cluster.main"
else
    log_success "✅ Cluster not in Terraform state (will be created)"
fi

cd ..

log_info "Next Steps:"
echo "1. Fix auto-scaling configuration in Terraform"
echo "2. Remove cluster from state if needed"
echo "3. Apply Terraform to create cluster in new subscription"
