#!/bin/bash
#
# Deployment Configuration
# Centralized configuration for The Order deployment automation
#

set -euo pipefail

# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly MAGENTA='\033[0;35m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m' # No Color

# Project configuration
readonly PROJECT_NAME="the-order"
readonly PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
readonly SCRIPTS_DIR="${PROJECT_ROOT}/scripts"
readonly INFRA_DIR="${PROJECT_ROOT}/infra"
readonly TERRAFORM_DIR="${INFRA_DIR}/terraform"
readonly K8S_DIR="${INFRA_DIR}/k8s"

# Azure configuration
readonly AZURE_REGION="${AZURE_REGION:-westeurope}"
readonly AZURE_SUBSCRIPTION_ID="${AZURE_SUBSCRIPTION_ID:-}"

# Region abbreviation mapping
get_region_abbrev() {
  case "${AZURE_REGION}" in
    westeurope) echo "we" ;;
    northeurope) echo "ne" ;;
    uksouth) echo "uk" ;;
    switzerlandnorth) echo "ch" ;;
    norwayeast) echo "no" ;;
    francecentral) echo "fr" ;;
    germanywestcentral) echo "de" ;;
    *) echo "we" ;; # Default to westeurope
  esac
}

# Environment abbreviation mapping
get_env_abbrev() {
  case "${ENVIRONMENT:-dev}" in
    dev) echo "dev" ;;
    stage) echo "stg" ;;
    prod) echo "prd" ;;
    mgmt) echo "mgmt" ;;
    *) echo "dev" ;;
  esac
}

# Naming convention: {provider}-{region}-{resource}-{env}-{purpose}
readonly REGION_SHORT=$(get_region_abbrev)
readonly ENV_SHORT=$(get_env_abbrev)
readonly NAME_PREFIX="az-${REGION_SHORT}"

# Environment configuration
readonly ENVIRONMENT="${ENVIRONMENT:-dev}"
readonly NAMESPACE="the-order-${ENVIRONMENT}"

# Resource Groups (az-we-rg-dev-main)
readonly RESOURCE_GROUP_NAME="${RESOURCE_GROUP_NAME:-${NAME_PREFIX}-rg-${ENV_SHORT}-main}"
readonly AKS_RESOURCE_GROUP="${AKS_RESOURCE_GROUP:-${RESOURCE_GROUP_NAME}}"

# Container registry (azweacrdev - alphanumeric only, max 50 chars)
readonly ACR_NAME="${ACR_NAME:-az${REGION_SHORT}acr${ENV_SHORT}}"
readonly IMAGE_TAG="${IMAGE_TAG:-latest}"

# Kubernetes configuration (az-we-aks-dev-main)
readonly AKS_NAME="${AKS_NAME:-${NAME_PREFIX}-aks-${ENV_SHORT}-main}"

# Key Vault (az-we-kv-dev-main - max 24 chars)
readonly KEY_VAULT_NAME="${KEY_VAULT_NAME:-${NAME_PREFIX}-kv-${ENV_SHORT}-main}"

# Database (az-we-psql-dev-main)
readonly POSTGRES_SERVER_NAME="${POSTGRES_SERVER_NAME:-${NAME_PREFIX}-psql-${ENV_SHORT}-main}"
readonly POSTGRES_DB_NAME="${POSTGRES_DB_NAME:-${NAME_PREFIX}-db-${ENV_SHORT}-main}"

# Storage (azwesadevdata - alphanumeric only, max 24 chars)
readonly STORAGE_ACCOUNT_NAME="${STORAGE_ACCOUNT_NAME:-az${REGION_SHORT}sa${ENV_SHORT}data}"

# Services
readonly SERVICES=("identity" "intake" "finance" "dataroom")
readonly APPS=("portal-public" "portal-internal")

# Service ports
declare -A SERVICE_PORTS=(
  ["identity"]="4002"
  ["intake"]="4001"
  ["finance"]="4003"
  ["dataroom"]="4004"
  ["portal-public"]="3000"
  ["portal-internal"]="3001"
)

# Logging
readonly LOG_DIR="${PROJECT_ROOT}/logs"
readonly LOG_FILE="${LOG_DIR}/deployment-$(date +%Y%m%d-%H%M%S).log"

# Deployment state
readonly STATE_DIR="${PROJECT_ROOT}/.deployment"
readonly STATE_FILE="${STATE_DIR}/${ENVIRONMENT}.state"

# Create necessary directories
mkdir -p "${LOG_DIR}"
mkdir -p "${STATE_DIR}"

# Logging functions
log_info() {
  echo -e "${BLUE}[INFO]${NC} $*" | tee -a "${LOG_FILE}"
}

log_success() {
  echo -e "${GREEN}[SUCCESS]${NC} $*" | tee -a "${LOG_FILE}"
}

log_warning() {
  echo -e "${YELLOW}[WARNING]${NC} $*" | tee -a "${LOG_FILE}"
}

log_error() {
  echo -e "${RED}[ERROR]${NC} $*" | tee -a "${LOG_FILE}"
}

log_step() {
  echo -e "${CYAN}[STEP]${NC} $*" | tee -a "${LOG_FILE}"
}

# Error handling
error_exit() {
  log_error "$1"
  exit "${2:-1}"
}

# Validation functions
check_command() {
  if ! command -v "$1" &> /dev/null; then
    error_exit "$1 is not installed. Please install it first."
  fi
}

check_azure_login() {
  if ! az account show &> /dev/null; then
    log_warning "Not logged into Azure. Attempting login..."
    az login || error_exit "Failed to login to Azure"
  fi
}

check_prerequisites() {
  log_info "Checking prerequisites..."
  check_command "node"
  check_command "pnpm"
  check_command "az"
  check_command "terraform"
  check_command "kubectl"
  check_command "docker"
  log_success "All prerequisites met"
}

# State management
save_state() {
  local phase="$1"
  local step="$2"
  echo "{\"phase\":\"${phase}\",\"step\":\"${step}\",\"timestamp\":\"$(date -Iseconds)\"}" > "${STATE_FILE}"
}

load_state() {
  if [ -f "${STATE_FILE}" ]; then
    cat "${STATE_FILE}"
  else
    echo "{\"phase\":\"none\",\"step\":\"none\"}"
  fi
}

# Export functions
export -f log_info log_success log_warning log_error log_step error_exit
export -f check_command check_azure_login check_prerequisites
export -f save_state load_state

