#[perlmod::package(name = "PMG::RS::CSR")]
pub mod export {
    use std::collections::HashMap;

    use anyhow::Error;
    use serde_bytes::ByteBuf;

    use proxmox_acme::util::{Csr, CsrKeyType, CsrOptions};

    /// Generates a CSR and its accompanying private key.
    ///
    /// The CSR is DER formatted, the private key is a PEM formatted pkcs8 private key.
    #[export]
    pub fn generate_csr(
        identifiers: Vec<&str>,
        attributes: HashMap<String, &str>,
        key_type: Option<String>,
        private_key_pem: Option<String>,
    ) -> Result<(ByteBuf, ByteBuf), Error> {
        let key_type = match key_type {
            Some(key_type) => CsrKeyType::parse(&key_type)?,
            None => CsrKeyType::default(),
        };

        let private_key_pem = private_key_pem.as_deref().map(str::as_bytes);
        let options = CsrOptions {
            key_type,
            private_key_pem,
        };

        let csr = Csr::generate_with_options(&identifiers, &attributes, &options)?;
        Ok((ByteBuf::from(csr.data), ByteBuf::from(csr.private_key_pem)))
    }
}
