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

use crate::types::SojuBouncer;

pub fn build_certificate(bouncer: &SojuBouncer) -> Certificate {
    let name = bouncer.metadata.name.clone().unwrap();
    let ns = bouncer.metadata.namespace.clone().unwrap();
    let tls = bouncer.spec.tls.as_ref().unwrap();
    let oref = bouncer.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_bouncer;

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

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

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

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