resource "kubernetes_namespace" "mail" {
  metadata {
    annotations = {
      name = "mail"
    }
    labels = {
      name = "mail"
    }
    name = "mail"
  }
}

resource "kubernetes_secret" "relay_mail_credentials" {
  metadata {
    name      = "relay-mail-credentials"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }
  data = {
    username = var.relay_smtp_username
    password = var.relay_smtp_password
  }
  type = "Opaque"
}

resource "kubernetes_service_account" "mail_app" {

  metadata {
    name      = "mail-app-sa"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }

  automount_service_account_token = false
}

resource "kubernetes_manifest" "mail_certificate" {
  manifest = {
    apiVersion = "cert-manager.io/v1"
    kind       = "Certificate"
    metadata = {
      name      = "mail-cert"
      namespace = kubernetes_namespace.mail.metadata[0].name
    }
    spec = {
      secretName = "mail-tls"
      issuerRef = {
        name = "letsencrypt-prod"
        kind = "ClusterIssuer"
      }
      commonName = "imap.${var.primary_domain}"
      dnsNames = flatten([for account in var.email_accounts : [
        "imap.${account.domain}",
        "smtp.${account.domain}"
      ]])
    }
  }
}

module "cert_checker" {
  source            = "../../utils/cert_checker"
  namespace         = kubernetes_namespace.mail.metadata[0].name
  persistent_folder = local.mail_path
  deployments       = local.deployments
}
