resource "google_container_cluster" "main" {
  name     = local.cluster_name
  location = var.region

  network    = google_compute_network.main.id
  subnetwork = google_compute_subnetwork.main.id

  # Autopilot: Google manages nodes, scales pools, autoscales node count,
  # and enforces opinionated security defaults. Less knob surface, less to
  # break — right call for "Atlas-style hosted datalake". Switch to
  # Standard mode if a customer needs custom node-pool isolation that
  # Autopilot's per-pod scheduling can't satisfy.
  enable_autopilot = true

  ip_allocation_policy {
    cluster_secondary_range_name  = "pods"
    services_secondary_range_name = "services"
  }

  release_channel {
    channel = var.release_channel
  }

  # Workload Identity is on by default in Autopilot — pods assume a GCP
  # service account via the `iam.gke.io/gcp-service-account` annotation on
  # their KSA. Equivalent to AWS IRSA. The service plane will use this in
  # phase 6 when the data plane talks to GCS for the archive tier.
  workload_identity_config {
    workload_pool = "${var.project_id}.svc.id.goog"
  }

  # Master endpoint stays public for now — same posture as cluster-aws.
  # Tighten via master_authorized_networks_config below or flip to
  # `enable_private_endpoint = true` when PrivateLink/IAP work lands.
  master_authorized_networks_config {
    dynamic "cidr_blocks" {
      for_each = var.master_authorized_networks
      content {
        cidr_block   = cidr_blocks.value.cidr_block
        display_name = cidr_blocks.value.display_name
      }
    }
  }

  # Surface control-plane logs & metrics to Cloud Logging / Monitoring so
  # the SRE team isn't blind on day 1. Autopilot bills for these by default.
  logging_config {
    enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"]
  }

  monitoring_config {
    enable_components = ["SYSTEM_COMPONENTS"]
    managed_prometheus {
      enabled = true
    }
  }

  # Deletion protection defaults on for prod environments. Staging users
  # can flip via the environment label.
  deletion_protection = var.environment == "prod"

  resource_labels = {
    component = "cluster"
  }
}

# Look up the project number — Workload Identity bindings use it in the
# `serviceAccount:<project>.svc.id.goog[<namespace>/<ksa>]` subject form.
data "google_project" "main" {
  project_id = var.project_id
}
