resource "azurerm_kubernetes_cluster" "main" {
  name                = local.cluster_name
  resource_group_name = azurerm_resource_group.main.name
  location            = azurerm_resource_group.main.location
  dns_prefix          = local.cluster_name
  kubernetes_version  = length(var.k8s_version) > 0 ? var.k8s_version : null

  tags = local.common_tags

  # System node pool — runs kube-system workloads (CoreDNS, metrics-server,
  # CSI controllers, etc.). One node is enough for shared-cluster workloads
  # in MVP; scale up via the auto_scaling block on the user pool below.
  default_node_pool {
    name           = "system"
    vm_size        = var.system_node_vm_size
    node_count     = 1
    vnet_subnet_id = azurerm_subnet.nodes.id

    only_critical_addons_enabled = true # taint: CriticalAddonsOnly=true:NoSchedule

    upgrade_settings {
      max_surge = "10%"
    }
  }

  # System-assigned managed identity. The principal id below is what we'd
  # grant RBAC to if the cluster needed read-only access to a key vault, etc.
  identity {
    type = "SystemAssigned"
  }

  # CNI Overlay mode — pod IPs come from `pod_cidr` rather than the VNet,
  # which means we don't burn IPv4 space on pod density. Service IPs come
  # from `service_cidr`.
  network_profile {
    network_plugin      = "azure"
    network_plugin_mode = "overlay"
    pod_cidr            = var.pod_cidr
    service_cidr        = var.service_cidr
    dns_service_ip      = var.dns_service_ip
    load_balancer_sku   = "standard"
  }

  # Workload Identity Federation (IRSA equivalent). Both flags must be on
  # for pods to assume Azure SPs via service-account annotations.
  oidc_issuer_enabled       = true
  workload_identity_enabled = true

  # Local accounts stay enabled in MVP — that's what makes
  # `kube_admin_config_raw` work without `kubelogin`. Production should
  # disable this and switch to AAD-backed kubeconfig.
  local_account_disabled = false

  # AKS clusters get auto-upgrade by default in patch channel. Surface it
  # so the operator knows.
  automatic_upgrade_channel = "patch"

  role_based_access_control_enabled = true
}

# User node pool — where the service plane (and large-tier datalake
# workloads) actually run. Autoscaling on, taint-free so pods land here
# rather than the tainted system pool.
resource "azurerm_kubernetes_cluster_node_pool" "user" {
  name                  = "user"
  kubernetes_cluster_id = azurerm_kubernetes_cluster.main.id
  vm_size               = var.node_vm_size
  vnet_subnet_id        = azurerm_subnet.nodes.id

  auto_scaling_enabled = true
  min_count            = var.node_min_count
  max_count            = var.node_max_count

  node_labels = {
    "aries.xylabs.com/pool" = "shared"
  }

  upgrade_settings {
    max_surge = "33%"
  }

  tags = local.common_tags
}
