# Azure Kubernetes Service (AKS) Configuration

variable "aks_cluster_name" {
  description = "Name of the AKS cluster"
  type        = string
  default     = ""
}

variable "aks_node_count" {
  description = "Number of nodes in the AKS cluster"
  type        = number
  default     = 2
}

variable "aks_vm_size" {
  description = "VM size for AKS nodes"
  type        = string
  default     = "Standard_B2s"
}

resource "azurerm_kubernetes_cluster" "main" {
  name                = var.aks_cluster_name != "" ? var.aks_cluster_name : "the-order-aks-${var.environment}"
  location            = var.azure_region
  resource_group_name = azurerm_resource_group.main.name
  dns_prefix          = "the-order-${var.environment}"
  kubernetes_version  = "1.28" # Update to latest stable
  
  # Use subscription_id from variable if provided
  # This ensures proper Azure authentication

  default_node_pool {
    name                = "default"
    node_count          = var.aks_node_count
    vm_size             = var.aks_vm_size
    type                = "VirtualMachineScaleSets"
    enable_auto_scaling = var.environment != "dev"
    min_count           = var.environment != "dev" ? 2 : null
    max_count           = var.environment != "dev" ? 10 : null
    os_disk_size_gb     = 30
  }

  identity {
    type = "SystemAssigned"
  }

  # Enable Azure RBAC
  azure_active_directory_role_based_access_control {
    managed                = true
    azure_rbac_enabled     = true
    admin_group_object_ids = [] # Add admin group IDs
  }

  # Network profile
  network_profile {
    network_plugin    = "azure"
    network_policy    = "azure"
    load_balancer_sku = "standard"
  }

  # Enable monitoring
  oms_agent {
    log_analytics_workspace_id = azurerm_log_analytics_workspace.main[0].id
  }

  tags = var.tags
}

# Log Analytics Workspace for AKS monitoring
resource "azurerm_log_analytics_workspace" "main" {
  count               = var.create_aks_cluster ? 1 : 0
  name                = "the-order-logs-${var.environment}"
  location            = var.azure_region
  resource_group_name = azurerm_resource_group.main.name
  sku                 = "PerGB2018"
  retention_in_days    = var.environment == "prod" ? 90 : 30

  tags = var.tags
}

# Output AKS details
output "aks_cluster_name" {
  value       = var.create_aks_cluster ? azurerm_kubernetes_cluster.main[0].name : null
  description = "Name of the AKS cluster"
}

output "aks_fqdn" {
  value       = var.create_aks_cluster ? azurerm_kubernetes_cluster.main[0].fqdn : null
  description = "FQDN of the AKS cluster"
}

output "aks_kube_config" {
  value       = var.create_aks_cluster ? azurerm_kubernetes_cluster.main[0].kube_config_raw : null
  description = "Raw Kubernetes config"
  sensitive   = true
}

output "log_analytics_workspace_id" {
  value       = azurerm_log_analytics_workspace.main[0].workspace_id
  description = "Log Analytics Workspace ID"
}

