/**
 * Well-Architected Framework Implementation
 * Main entry point for deploying Well-Architected infrastructure
 */

terraform {
  required_version = ">= 1.5.0"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

# Data sources
data "azurerm_client_config" "current" {}
data "azurerm_subscription" "current" {}

# Load environment variables
locals {
  environment = var.environment != "" ? var.environment : (var.ENVIRONMENT != "" ? var.ENVIRONMENT : "dev")
  region      = var.azure_region != "" ? var.azure_region : (var.AZURE_LOCATION != "" ? var.AZURE_LOCATION : "westeurope")
  
  # Management group ID from environment or variable
  management_group_id = var.management_group_id != "" ? var.management_group_id : (var.AZURE_MANAGEMENT_GROUP_ID != "" ? var.AZURE_MANAGEMENT_GROUP_ID : "")
}

# Resource Group
resource "azurerm_resource_group" "well_architected" {
  name     = "rg-well-architected-${local.environment}"
  location = local.region

  tags = {
    Environment     = local.environment
    Project         = "the-order"
    CostCenter      = "legal-services"
    Owner           = "legal-team"
    DataClassification = "confidential"
    Sovereignty     = "required"
    ManagedBy       = "terraform"
    WellArchitected = "true"
  }
}

# Well-Architected Module
module "well_architected" {
  source = "../modules/well-architected"

  name_prefix         = "the-order"
  environment         = local.environment
  region              = local.region
  resource_group_name = azurerm_resource_group.well_architected.name
  resource_group_id   = azurerm_resource_group.well_architected.id

  # Cost Optimization
  enable_cost_management     = true
  monthly_budget_amount      = var.monthly_budget_amount
  budget_alert_emails        = var.budget_alert_emails
  cost_export_storage_container_id = var.cost_export_storage_container_id

  # Operational Excellence
  enable_automation = true

  # Performance Efficiency
  enable_front_door = var.enable_front_door
  backend_host_header = var.backend_host_header
  backend_address     = var.backend_address
  enable_redis_cache  = true
  redis_capacity      = local.environment == "production" ? 2 : 1
  redis_family        = "C"

  # Reliability
  enable_backup = true

  # Security
  create_key_vault      = false # Use existing Key Vault
  enable_defender       = true
  enable_ddos_protection = true

  # Cloud for Sovereignty
  enable_sovereignty_policies = true
  allowed_regions            = var.allowed_regions
  management_group_id        = local.management_group_id

  tags = {
    WellArchitected = "true"
  }
}

