resource "tls_private_key" "tls" {
  algorithm = "ED25519"
}

resource "tls_self_signed_cert" "tls" {
  private_key_pem = tls_private_key.tls.private_key_pem

  subject {
    common_name  = "kube-ca"
    organization = "Alexandre Pires, Portugal"
  }

  validity_period_hours = 87600
  is_ca_certificate     = true

  allowed_uses = [
    "cert_signing",
    "key_encipherment",
    "digital_signature",
    "crl_signing"
  ]
}

resource "kubernetes_secret" "root_ca" {
  metadata {
    name      = "root-ca"
    namespace = "cert-manager"
  }
  data = {
    "tls.crt" = tls_self_signed_cert.tls.cert_pem
    "tls.key" = tls_private_key.tls.private_key_pem
  }

  type = "kubernetes.io/tls"
}

resource "kubernetes_manifest" "cluster_issuer" {

  manifest = {
    apiVersion = "cert-manager.io/v1"
    kind       = "ClusterIssuer"
    metadata = {
      name = local.internal_issuer
      annotations = {
        "cert-manager.io/issuer-group" = "cert-manager.io"
        "cert-manager.io/issuer-kind"  = "Issuer"
        "cert-manager.io/issuer-name"  = local.internal_issuer
      }
    }
    spec = {
      ca = {
        secretName = "root-ca"
      }
    }
  }
}
