use k8s_openapi::api::core::v1::Secret;
use kube::api::ObjectMeta;
use kube::Resource;
use std::collections::BTreeMap;

use crate::types::SojuBouncer;

pub fn build_db_secret(bouncer: &SojuBouncer, connection_uri: &str, password: &str) -> Secret {
    let name = bouncer.metadata.name.clone().unwrap();
    let ns = bouncer.metadata.namespace.clone().unwrap();
    let oref = bouncer.controller_owner_ref(&()).unwrap();

    Secret {
        metadata: ObjectMeta {
            name: Some(format!("{name}-db")),
            namespace: Some(ns),
            owner_references: Some(vec![oref]),
            ..Default::default()
        },
        string_data: Some(BTreeMap::from([
            ("uri".to_string(), connection_uri.to_string()),
            ("password".to_string(), password.to_string()),
        ])),
        ..Default::default()
    }
}

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

    #[test]
    fn secret_named_correctly() {
        let s = build_db_secret(&test_bouncer(), "host=db dbname=test");
        assert_eq!(s.metadata.name.unwrap(), "test-bouncer-db");
    }

    #[test]
    fn secret_contains_uri_key() {
        let s = build_db_secret(&test_bouncer(), "host=db dbname=test");
        let data = s.string_data.unwrap();
        assert_eq!(data["uri"], "host=db dbname=test");
    }

    #[test]
    fn secret_has_owner_reference() {
        let s = build_db_secret(&test_bouncer(), "host=db dbname=test");
        let orefs = s.metadata.owner_references.unwrap();
        assert_eq!(orefs[0].name, "test-bouncer");
    }
}
