#!/bin/bash
# Complete Azure deployment script
# Uses environment variables from .env file

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
TERRAFORM_DIR="$PROJECT_ROOT/infra/terraform"

echo "🚀 Starting Azure deployment..."

# Load environment variables
source "$SCRIPT_DIR/azure-load-env.sh"

# Change to Terraform directory
cd "$TERRAFORM_DIR"

# Initialize Terraform
echo "📦 Initializing Terraform..."
terraform init

# Validate configuration
echo "✅ Validating Terraform configuration..."
terraform validate

# Plan deployment
echo "📋 Planning deployment..."
terraform plan -out=tfplan

# Ask for confirmation
read -p "Do you want to apply these changes? (yes/no): " -r
if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
  echo "Deployment cancelled."
  exit 0
fi

# Apply changes
echo "🔨 Applying Terraform configuration..."
terraform apply tfplan

# Get outputs
echo ""
echo "📊 Deployment outputs:"
terraform output

# Save kubeconfig if AKS was created
if terraform output -raw aks_kube_config > /dev/null 2>&1; then
  KUBECONFIG_FILE="$PROJECT_ROOT/.kube/config"
  mkdir -p "$(dirname "$KUBECONFIG_FILE")"
  terraform output -raw aks_kube_config > "$KUBECONFIG_FILE"
  echo ""
  echo "✅ Kubernetes config saved to: $KUBECONFIG_FILE"
  echo "   You can now use: kubectl --kubeconfig=$KUBECONFIG_FILE get nodes"
fi

echo ""
echo "✅ Azure deployment complete!"

