locals {
  cluster_config = yamldecode(data.minio_s3_object.k8s_yaml.content)
  cluster_server = local.cluster_config.clusters[0].cluster.server
  cluster_auth = try(
    {
      token       = local.cluster_config.users[0].user.token
      using_token = true
    },
    {
      client_certificate = base64decode(local.cluster_config.users[0].user["client-certificate-data"])
      client_key = base64decode(local.cluster_config.users[0].user["client-key-data"])
      using_token = false
    }
  )
}

resource "kubernetes_secret" "app-365zon-cluster" {
  depends_on = [var.wait_on]

  metadata {
    name      = "app-365zon-cluster-secret"
    namespace = "argocd"
    labels = {
      "argocd.argoproj.io/secret-type" = "cluster"
    }
  }

  type = "Opaque"
  data = {
    name   = "app-365zon"
    server = local.cluster_server
    config = local.cluster_auth.using_token ? jsonencode({
      "bearerToken" = local.cluster_auth.token
    }) : jsonencode({
      "tlsClientConfig" = {
        "insecure" = true
        "certData" = base64encode(local.cluster_auth.client_certificate)
        "keyData" = base64encode(local.cluster_auth.client_key)
      }
    })
  }
}

output "installed" {
  value = true
  depends_on = [kubernetes_secret.app-365zon-cluster]
}
