resource "kubernetes_namespace" "mongodb" {
  metadata {
    name = var.namespace
  }

  lifecycle {
    ignore_changes = [metadata]
  }
}

resource "random_password" "mongodb_root_password" {
  length  = 40
  special = false
}

resource "random_password" "mongodb_replica_set_key" {
  length  = 40
  special = false
}

resource "kubernetes_secret" "mongodb_auth" {
  type = "generic"
  depends_on = [var.wait_on]
  metadata {
    name      = "mongodb-auth"
    namespace = kubernetes_namespace.mongodb.metadata.0.name
  }

  data = {
    mongodb-root-password   = random_password.mongodb_root_password.result
    mongodb-replica-set-key = random_password.mongodb_replica_set_key.result
  }
}

resource "helm_release" "mongodb" {
  depends_on = [var.wait_on, kubernetes_secret.mongodb_auth]
  name             = "mongodb"
  repository       = "oci://registry-1.docker.io/bitnamicharts"
  chart            = "mongodb"
  namespace        = kubernetes_namespace.mongodb.metadata.0.name
  version          = "16.3.1"
  create_namespace = false
  wait             = true
  wait_for_jobs    = true

  values = [
    templatefile("${path.module}/values.yaml", {
      usernames = var.usernames,
      databases = var.databases,
      replicas  = var.replicas
    })
  ]
}

output "installed" {
  value = true
  depends_on = [helm_release.mongodb]
}

output "connection_string" {
  value = format(
    "mongodb://%s:%s@%s/%s?replicaSet=rs0&authSource=admin",
    "root",
    random_password.mongodb_root_password.result,
    join(",", [
      for i in range(var.replicas) :format("mongodb-%d.mongodb-headless.mongodb.svc.cluster.local:27017", i)
    ]),
    "admin"
  )
  sensitive = true
}
