# Global Multi-Region Deployment Configuration
# Validator nodes in ALL non-US Commercial Azure regions with SAME VM size
# RPC nodes in ALL regions (core backbone)
# System and sentry nodes distributed as needed

locals {
  # Treat West Europe as admin/control-plane only (no workload AKS here)
  admin_region = "westeurope"
  # Standard VM size for ALL node pools in 36 workload regions - Dplsv6 Family
  # Using D2plsv6 (2 vCPUs) so that even 2 system + 2 validator + 1 RPC nodes stay <= 10 vCPUs/region
  standard_vm_size = "Standard_D2plsv6"  # 2 vCPUs - Dplsv6 Family
  
  # All non-US Commercial Azure regions
  all_non_us_regions = [
    "belgiumcentral",
    "brazilsouth",
    "canadacentral",
    "canadaeast",
    "centralindia",
    "chilecentral",
    "eastasia",
    "francecentral",
    "germanywestcentral",
    "indonesiacentral",
    "israelcentral",
    "italynorth",
    "japaneast",
    "japanwest",
    "koreacentral",
    "koreasouth",
    "malaysiawest",
    "mexicocentral",
    "newzealandnorth",
    "northeurope",
    "norwayeast",
    "polandcentral",
    "qatarcentral",
    "southafricanorth",
    "southeastasia",
    "southindia",
    "spaincentral",
    "swedencentral",
    "switzerlandnorth",
    "uaenorth",
    "uksouth",
    "ukwest",
    "westeurope",
    "westindia"
  ]
  
  # Region code mapping for all regions
  global_region_codes = {
    belgiumcentral      = "bel"
    brazilsouth         = "bra"
    brazilsoutheast     = "bse"
    canadacentral       = "can"
    canadaeast          = "cae"
    centralindia        = "cin"
    chilecentral        = "chc"
    eastasia            = "eas"
    francecentral       = "frc"
    francesouth         = "frs"
    germanynorth        = "gno"
    germanywestcentral  = "gwc"
    indonesiacentral    = "idn"
    israelcentral       = "ilc"
    italynorth          = "ita"
    japaneast           = "jpe"
    japanwest           = "jpw"
    jioindiacentral     = "jic"
    jioindiawest        = "jiw"
    koreacentral        = "kor"
    koreasouth          = "kos"
    malaysiawest        = "mys"
    mexicocentral       = "mex"
    newzealandnorth     = "nzl"
    northeurope         = "nor"
    norwayeast          = "noe"
    norwaywest          = "now"
    polandcentral       = "pol"
    qatarcentral        = "qat"
    southafricanorth    = "san"
    southafricawest     = "saw"
    southeastasia       = "sea"
    southindia          = "sin"
    spaincentral        = "spa"
    swedencentral       = "swc"
    switzerlandnorth    = "swn"
    switzerlandwest     = "swt"
    uaecentral          = "uac"
    uaenorth            = "uan"
    uksouth             = "uks"
    ukwest              = "ukw"
    westeurope          = "wst"
    westindia           = "win"
  }
  
  # Multi-region configuration for ALL non-US regions (excluding admin region)
  # Validators: Same VM size in ALL regions
  # RPC: In ALL regions (core backbone)
  # System/Sentries: Distributed as needed
  # Regional overrides for node counts to reassign capacity
  regional_nodecount_overrides = {
    # Reassign +1 System +1 Validator from West Europe to these regions
    northeurope    = { system = 2, validators = 2 }
    belgiumcentral = { system = 2, validators = 2 }
  }

  global_multi_region_config = {
    for region in [for r in local.all_non_us_regions : r if r != local.admin_region] : region => {
      location      = region
      region_code   = lookup(local.global_region_codes, region, substr(region, 0, 2))
      
      # All node pools use Standard_D2plsv6 in 36 workload regions
      validator_vm_size = local.standard_vm_size
      rpc_vm_size        = local.standard_vm_size
      system_vm_size     = local.standard_vm_size
      sentry_vm_size     = local.standard_vm_size
      
      # Node counts - can be adjusted per region based on quotas
      # Validators: 1 per region (minimum for consensus)
      # RPC: 1 per region (core backbone)
      # System: 1 per region (AKS system pool)
      # Sentries: 0-1 per region (distributed as needed)
      node_count = merge(
        {
          system     = 1
          validators = 1
          sentries   = 0
          rpc        = 1
        },
        contains(keys(local.regional_nodecount_overrides), region)
          ? {
              system     = local.regional_nodecount_overrides[region].system
              validators = local.regional_nodecount_overrides[region].validators
            }
          : {}
      )
      
      # VM families for quota tracking - all use Standard_D2plsv6
      vm_families = {
        system     = local.standard_vm_size  # 2 vCPUs - Dplsv6 Family
        validators = local.standard_vm_size  # 2 vCPUs - Dplsv6 Family
        sentries   = local.standard_vm_size  # 2 vCPUs - Dplsv6 Family
        rpc        = local.standard_vm_size  # 2 vCPUs - Dplsv6 Family
      }
    }
  }
}

# Global multi-region resource groups
resource "azurerm_resource_group" "global_multi_region" {
  for_each = var.enable_multi_region ? local.global_multi_region_config : {}
  
  name     = "${local.cloud_provider}-${local.env_code}-${each.value.region_code}-rg-comp-001"
  location = each.value.location
  
  tags = merge(local.common_tags, {
    Region     = each.value.location
    Deployment = "global-multi-region"
    NodeType   = "validator-rpc"
  })
}

# Global multi-region AKS clusters
module "aks_global_multi_region" {
  for_each = var.enable_multi_region ? local.global_multi_region_config : {}
  source   = "./modules/kubernetes"
  
  resource_group_name = azurerm_resource_group.global_multi_region[each.key].name
  location            = each.value.location
  cluster_name        = "${local.cloud_provider}-${local.env_code}-${each.value.region_code}-aks-main"
  kubernetes_version  = var.kubernetes_version
  node_count          = each.value.node_count
  vm_size             = each.value.vm_families
  environment         = var.environment
  tags                = merge(local.common_tags, {
    Region     = each.value.location
    Deployment = "global-multi-region"
    ValidatorVM = each.value.validator_vm_size  # Track validator VM size
  })
  
  # Per-region networking
  vnet_subnet_id = module.networking_global_multi_region[each.key].aks_subnet_id
  node_subnet_id = module.networking_global_multi_region[each.key].node_subnet_id
  
  # Shared Key Vault (or per-region)
  key_vault_id = module.keyvault.key_vault_id
  
  depends_on = [
    azurerm_resource_group.global_multi_region,
    module.networking_global_multi_region
  ]
}

# Global multi-region networking
module "networking_global_multi_region" {
  for_each = var.enable_multi_region ? local.global_multi_region_config : {}
  source   = "./modules/networking"
  
  resource_group_name = azurerm_resource_group.global_multi_region[each.key].name
  location            = each.value.location
  cluster_name        = "${local.cloud_provider}-${local.env_code}-${each.value.region_code}-aks-main"
  environment         = var.environment
  tags                = merge(local.common_tags, {
    Region     = each.value.location
    Deployment = "global-multi-region"
  })
}

# Global multi-region storage
module "storage_global_multi_region" {
  for_each = var.enable_multi_region ? local.global_multi_region_config : {}
  source   = "./modules/storage"
  
  resource_group_name = azurerm_resource_group.global_multi_region[each.key].name
  location            = each.value.location
  cluster_name        = "${local.cloud_provider}-${local.env_code}-${each.value.region_code}-aks-main"
  environment         = var.environment
  tags                = merge(local.common_tags, {
    Region     = each.value.location
    Deployment = "global-multi-region"
  })
}

# Outputs for global multi-region deployment
output "global_multi_region_clusters" {
  value = var.enable_multi_region ? {
    for k, v in module.aks_global_multi_region : k => {
      cluster_name    = v.cluster_name
      cluster_fqdn    = v.cluster_fqdn
      location        = local.global_multi_region_config[k].location
      vm_size         = local.standard_vm_size
      validator_count = local.global_multi_region_config[k].node_count.validators
      rpc_count       = local.global_multi_region_config[k].node_count.rpc
      system_count    = local.global_multi_region_config[k].node_count.system
      sentry_count    = local.global_multi_region_config[k].node_count.sentries
    }
  } : {}
  description = "Global multi-region AKS cluster information (all node pools use Standard_D2plsv6)"
}

output "validator_regions_summary" {
  value = var.enable_multi_region ? {
    total_regions     = length(local.all_non_us_regions)
    vm_size           = local.standard_vm_size
    regions           = [for r in local.all_non_us_regions : r]
  } : {
    total_regions     = 0
    vm_size           = ""
    regions           = []
  }
  description = "Summary of deployment across all non-US regions (all node pools use Standard_D2plsv6)"
}

