#!/bin/bash
# Sync environment variables from .env to Terraform variables
# Ensures Terraform uses values from .env file

set -e

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

echo "🔄 Syncing environment variables to Terraform..."

# Load and validate environment
source "$SCRIPT_DIR/azure-validate-env.sh"

# Create terraform.tfvars from environment variables
TFVARS_FILE="$TERRAFORM_DIR/terraform.tfvars"

cat > "$TFVARS_FILE" << EOF
# Terraform variables generated from .env file
# DO NOT EDIT MANUALLY - regenerated by azure-sync-env-to-terraform.sh
# Last updated: $(date -u +"%Y-%m-%d %H:%M:%S UTC")

# Azure Configuration
azure_region = "${ARM_LOCATION:-westeurope}"
environment = "${TF_VAR_environment:-dev}"
project_name = "the-order"

# Azure Authentication (sensitive - use environment variables)
# subscription_id = "${ARM_SUBSCRIPTION_ID}"
# tenant_id = "${ARM_TENANT_ID}"
# client_id = "${ARM_CLIENT_ID:-}"
# client_secret = "${ARM_CLIENT_SECRET:-}"

# Resource Naming
resource_group_name = "${TF_VAR_resource_group_name}"
storage_account_name = "${TF_VAR_storage_account_name}"
key_vault_name = "${TF_VAR_key_vault_name}"

# AKS Configuration
aks_cluster_name = "${TF_VAR_aks_cluster_name:-the-order-aks-${TF_VAR_environment:-dev}}"
aks_node_count = ${TF_VAR_aks_node_count:-2}
aks_vm_size = "${TF_VAR_aks_vm_size:-Standard_B2s}"

# Database Configuration
database_name = "${TF_VAR_database_name:-the-order-db-${TF_VAR_environment:-dev}}"
database_admin_user = "${TF_VAR_database_admin_user:-theorder_admin}"

# Tags
tags = {
  Environment = "${TF_VAR_environment:-dev}"
  Project     = "the-order"
  ManagedBy   = "terraform"
  CreatedBy   = "azure-sync-env-to-terraform.sh"
}
EOF

echo "✅ Terraform variables synced to: $TFVARS_FILE"
echo ""
echo "You can now run Terraform commands:"
echo "  cd $TERRAFORM_DIR"
echo "  terraform init"
echo "  terraform plan"
echo "  terraform apply"

