terraform {
  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "2.31.0"
    }
  }
}

resource "kubernetes_namespace" "zitadel" {
  count = var.enabled ? 1 : 0
  metadata {
    name = var.namespace
  }

  lifecycle {
    ignore_changes = [metadata]
  }
}

resource "random_password" "zitadel_masterkey" {
  length  = 32
  special = true
}

resource "kubernetes_secret" "zitadel" {
  count = var.enabled ? 1 : 0
  metadata {
    name      = "zitadel"
    namespace = kubernetes_namespace.zitadel[count.index].metadata[0].name
  }
  data = {
    masterkey = random_password.zitadel_masterkey.result
  }
}

resource "helm_release" "zitadel" {
  count            = var.enabled ? 1 : 0
  depends_on = [var.wait_on, kubernetes_secret.zitadel]
  name             = "zitadel"
  repository       = "https://charts.zitadel.com"
  chart            = "zitadel"
  namespace = kubernetes_namespace.zitadel[count.index].metadata[0].name
  version          = "8.12.0"
  create_namespace = false
  wait             = true
  wait_for_jobs    = true

  values = [
    templatefile("${path.module}/values.yaml.tftpl", {
      service_uri            = local.service_uri,
      database               = var.database,
      database_username      = var.database_username,
      database_password      = var.database_password,
      database_root_username = var.database_root_password != null ? var.database_root_username : null,
      database_root_password = var.database_root_password
      display_on_homepage    = var.display_on_homepage
      ingressClass           = var.ingressClass
    })
  ]
}

data "kubernetes_secret" "zitadel_admin" {
  depends_on = [helm_release.zitadel]
  metadata {
    name      = "zitadel-admin-sa"
    namespace = var.namespace
  }
}

resource "local_file" "zitadel_jwt_profile_file" {
  content = data.kubernetes_secret.zitadel_admin.data["zitadel-admin-sa.json"]
  filename = format("%s/%s", path.root, "zitadel-admin-sa.json")
}

output "jwt_profile_file" {
  value = local_file.zitadel_jwt_profile_file.filename
}

output "installed" {
  value = true
  depends_on = [helm_release.zitadel, local_file.zitadel_jwt_profile_file]
}

output "server" {
  value = local.service_uri
}

output "uri" {
  value = "https://${local.service_uri}"
}
