# =============================================================================
# EKS cluster + Bottlerocket worker node group (single AZ)
# =============================================================================

data "aws_subnet" "vpc_subnets" {
  count = length(module.vpc.private_subnets)
  id    = module.vpc.private_subnets[count.index]
}

locals {
  # Worker nodes live in a single AZ (availability_zones[0]), same as the eksctl setup
  node_group_subnet_ids = [
    for subnet in data.aws_subnet.vpc_subnets : subnet.id
    if subnet.availability_zone == var.availability_zones[0]
  ]

  # Pre-existing customer managed policies attached to the worker node role
  node_customer_policies = {
    autonomous-o11y-rs-data    = "arn:aws:iam::${local.o11y_account}:policy/autonomous-o11y-rs-data"
    autonomous-o11y-rs-control = "arn:aws:iam::${local.o11y_account}:policy/autonomous-o11y-rs-control"
  }
}

locals {
  # autonomous-cent-stor-dev exists in the dev/staging o11y account
  # (552185537300) but not in the prod account, matching the legacy
  # meta/o11y-{dev,staging}.yaml admin-roles. Appended everywhere except prod.
  admin_role_names = distinct(concat(
    var.admin_role_names,
    var.env == "prod" ? [] : ["autonomous-cent-stor-dev"],
  ))
}

module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 21.0"

  name                        = local.cluster_name
  kubernetes_version          = var.eks_version
  endpoint_private_access     = true
  endpoint_public_access      = true
  enable_irsa                 = true
  create_cloudwatch_log_group = false
  enabled_log_types           = []

  access_entries = merge(
    {
      for role_name in local.admin_role_names : role_name => {
        principal_arn = format("arn:aws:iam::%s:role/%s", local.o11y_account, role_name)
        type          = "STANDARD"
        policy_associations = {
          admin = {
            policy_arn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"
            access_scope = {
              type = "cluster"
            }
          }
        }
      }
    },
    {
      jump-service = {
        principal_arn = var.jump_service_account_role_arn
        type          = "STANDARD"
        policy_associations = {
          admin = {
            policy_arn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"
            access_scope = {
              type = "cluster"
            }
          }
        }
      }
    }
  )

  create_iam_role      = true
  create_node_iam_role = true

  addons = {
    vpc-cni = {
      before_compute    = true
      resolve_conflicts = "OVERWRITE"
      most_recent       = true
      configuration_values = jsonencode({
        env = {
          ENABLE_PREFIX_DELEGATION = "true"
        }
      })
    }
    coredns = {
      most_recent = true
    }
    kube-proxy = {
      most_recent = true
    }
    aws-ebs-csi-driver = {
      most_recent = true
    }
    metrics-server = {
      most_recent = true
    }
  }

  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets

  eks_managed_node_groups = {
    worker = {
      name            = "worker"
      use_name_prefix = false
      ami_type        = "BOTTLEROCKET_x86_64"
      instance_types  = [var.worker_instance_type]
      desired_size    = var.worker_desired_size
      min_size        = var.worker_min_size
      max_size        = var.worker_max_size
      subnet_ids      = local.node_group_subnet_ids
      labels = {
        node_type = "worker"
      }
      # Rendered as Bottlerocket TOML user data; EKS merges its own bootstrap
      # settings (cluster-name/api-server/certificate) with these settings.
      bootstrap_extra_args = <<-EOT
        [settings.kubernetes]
        "max-pods" = ${var.worker_max_pods_per_node}
      EOT
      metadata_options = {
        http_put_response_hop_limit = 2
      }
      iam_role_attach_cni_policy = true
      iam_role_additional_policies = merge({
        AmazonSSMManagedInstanceCore = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
        AmazonEBSCSIDriverPolicy     = "arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy"
      }, local.node_customer_policies)
    }
  }
  enable_cluster_creator_admin_permissions = true

  tags = local.common_tags
}

locals {
  eks = {
    name                       = module.eks.cluster_name
    endpoint                   = module.eks.cluster_endpoint
    certificate_authority_data = module.eks.cluster_certificate_authority_data
    oidc_issuer_url            = module.eks.cluster_oidc_issuer_url
    kubeconfig = yamlencode({
      apiVersion = "v1"
      kind       = "Config"
      clusters = [{
        name = module.eks.cluster_name
        cluster = {
          server                     = module.eks.cluster_endpoint
          certificate-authority-data = module.eks.cluster_certificate_authority_data
        }
      }]
      contexts = [{
        name = module.eks.cluster_name
        context = {
          cluster = module.eks.cluster_name
          user    = module.eks.cluster_name
        }
      }]
      current-context = module.eks.cluster_name
      users = [{
        name = module.eks.cluster_name
        user = {
          exec = {
            apiVersion = "client.authentication.k8s.io/v1beta1"
            command    = "aws"
            args = [
              "eks",
              "get-token",
              "--region", var.aws_region,
              "--cluster-name", module.eks.cluster_name,
              "--profile", local.o11y_account,
              "--output", "json"
            ]
          }
        }
      }]
    })
  }
}
