use k8s_crds_cert_manager::certificates::{
    Certificate, CertificateIssuerRef, CertificateSpec,
};
use kube::api::ObjectMeta;
use kube::Resource;

use crate::types::ErgoNetwork;

pub fn build_certificate(network: &ErgoNetwork) -> Certificate {
    let name = network.metadata.name.clone().unwrap();
    let ns = network.metadata.namespace.clone().unwrap();
    let tls = network.spec.tls.as_ref().unwrap();
    let oref = network.controller_owner_ref(&()).unwrap();

    Certificate {
        metadata: ObjectMeta {
            name: Some(name.clone()),
            namespace: Some(ns),
            owner_references: Some(vec![oref]),
            ..Default::default()
        },
        spec: CertificateSpec {
            secret_name: format!("{name}-tls"),
            issuer_ref: CertificateIssuerRef {
                name: tls.issuer_ref.name.clone(),
                kind: Some(tls.issuer_ref.kind.clone()),
                group: Some("cert-manager.io".to_string()),
            },
            dns_names: Some(tls.dns_names.clone()),
            ..Default::default()
        },
        status: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testutil::test_network;

    #[test]
    fn certificate_uses_issuer_from_spec() {
        let cert = build_certificate(&test_network());
        assert_eq!(cert.spec.issuer_ref.name, "letsencrypt-prod");
        assert_eq!(cert.spec.issuer_ref.kind, Some("ClusterIssuer".to_string()));
    }

    #[test]
    fn certificate_has_correct_dns_names() {
        let cert = build_certificate(&test_network());
        let dns = cert.spec.dns_names.as_ref().unwrap();
        assert_eq!(dns, &vec!["test-network.irc.now".to_string()]);
    }

    #[test]
    fn certificate_secret_name_matches_convention() {
        let cert = build_certificate(&test_network());
        assert_eq!(cert.spec.secret_name, "test-network-tls");
    }

    #[test]
    fn certificate_has_owner_reference() {
        let cert = build_certificate(&test_network());
        let orefs = cert.metadata.owner_references.unwrap();
        assert_eq!(orefs[0].name, "test-network");
    }
}
