#!/bin/bash
# Validate Azure environment variables from .env file
# Ensures all required variables are set for deployments

set -e

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

echo "🔍 Validating Azure environment configuration..."

# Load environment file if it exists
if [ -f "$ENV_FILE" ]; then
  echo "Loading environment from: $ENV_FILE"
  set -a
  source "$ENV_FILE"
  set +a
else
  echo "⚠️  No .env file found at: $ENV_FILE"
  echo "Creating from example..."
  if [ -f "$PROJECT_ROOT/infra/terraform/.env.example" ]; then
    cp "$PROJECT_ROOT/infra/terraform/.env.example" "$ENV_FILE"
    echo "✅ Created $ENV_FILE - please fill in your values"
  fi
  exit 1
fi

# Required Azure variables
REQUIRED_VARS=(
  "ARM_SUBSCRIPTION_ID"
  "ARM_TENANT_ID"
)

# Optional but recommended
RECOMMENDED_VARS=(
  "ARM_LOCATION"
  "TF_VAR_environment"
  "TF_VAR_resource_group_name"
  "TF_VAR_storage_account_name"
  "TF_VAR_key_vault_name"
)

# Check required variables
MISSING_REQUIRED=()
for var in "${REQUIRED_VARS[@]}"; do
  if [ -z "${!var}" ]; then
    MISSING_REQUIRED+=("$var")
  fi
done

# Check recommended variables
MISSING_RECOMMENDED=()
for var in "${RECOMMENDED_VARS[@]}"; do
  if [ -z "${!var}" ]; then
    MISSING_RECOMMENDED+=("$var")
  fi
done

# Report results
if [ ${#MISSING_REQUIRED[@]} -gt 0 ]; then
  echo "❌ Missing required variables:"
  for var in "${MISSING_REQUIRED[@]}"; do
    echo "   - $var"
  done
  echo ""
  echo "Please set these in your .env file."
  exit 1
fi

if [ ${#MISSING_RECOMMENDED[@]} -gt 0 ]; then
  echo "⚠️  Missing recommended variables (will use defaults):"
  for var in "${MISSING_RECOMMENDED[@]}"; do
    echo "   - $var"
  done
  echo ""
fi

# Validate Azure CLI authentication
if command -v az &> /dev/null; then
  if az account show &> /dev/null; then
    CURRENT_SUB=$(az account show --query id -o tsv)
    if [ "$CURRENT_SUB" != "$ARM_SUBSCRIPTION_ID" ]; then
      echo "⚠️  Azure CLI subscription ($CURRENT_SUB) differs from ARM_SUBSCRIPTION_ID"
      echo "   Setting Azure CLI to use: $ARM_SUBSCRIPTION_ID"
      az account set --subscription "$ARM_SUBSCRIPTION_ID" || true
    fi
  else
    echo "⚠️  Not logged in to Azure CLI. Run: az login"
  fi
else
  echo "⚠️  Azure CLI not installed. Install from: https://aka.ms/InstallAzureCLIDeb"
fi

# Set defaults for missing recommended vars
export ARM_LOCATION="${ARM_LOCATION:-westeurope}"
export TF_VAR_environment="${TF_VAR_environment:-dev}"
export TF_VAR_azure_region="${ARM_LOCATION}"

# Export Terraform variables
export TF_VAR_subscription_id="${ARM_SUBSCRIPTION_ID}"
export TF_VAR_tenant_id="${ARM_TENANT_ID}"
export TF_VAR_client_id="${ARM_CLIENT_ID:-}"
export TF_VAR_client_secret="${ARM_CLIENT_SECRET:-}"

# Generate resource names if not set
if [ -z "$TF_VAR_resource_group_name" ]; then
  export TF_VAR_resource_group_name="the-order-rg-${TF_VAR_environment}"
fi

if [ -z "$TF_VAR_storage_account_name" ]; then
  # Generate unique storage account name
  TIMESTAMP=$(date +%s | tail -c 5)
  export TF_VAR_storage_account_name="theorder${TF_VAR_environment}${TIMESTAMP}"
fi

if [ -z "$TF_VAR_key_vault_name" ]; then
  export TF_VAR_key_vault_name="the-order-kv-${TF_VAR_environment}"
fi

echo "✅ Environment validation complete!"
echo ""
echo "Azure Configuration:"
echo "  Subscription ID: ${ARM_SUBSCRIPTION_ID:0:8}..."
echo "  Tenant ID: ${ARM_TENANT_ID:0:8}..."
echo "  Location: ${ARM_LOCATION}"
echo "  Environment: ${TF_VAR_environment}"
echo "  Resource Group: ${TF_VAR_resource_group_name}"
echo "  Storage Account: ${TF_VAR_storage_account_name}"
echo "  Key Vault: ${TF_VAR_key_vault_name}"
echo ""
echo "All Terraform variables are set and ready for deployment."

