use rsa::pkcs8::DecodePublicKey;
use rsa::{Pkcs1v15Encrypt, RsaPublicKey};

use crate::Error;

pub(crate) fn rsa_base64_encrypt<T, E>(public_key: T, plaintext: E) -> Result<String, Error>
where
    T: AsRef<str>,
    E: AsRef<[u8]>,
{
    let mut rng = rand::rng();
    let public_key = RsaPublicKey::from_public_key_pem(public_key.as_ref())
        .map_err(|err| Error::Rsa(err.to_string()))?;

    let ciphertext = public_key
        .encrypt(&mut rng, Pkcs1v15Encrypt, plaintext.as_ref())
        .map_err(|err| Error::Rsa(err.to_string()))?;

    Ok(base64_simd::STANDARD.encode_to_string(ciphertext))
}

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

    #[test]
    fn rsa() -> Result<(), Error> {
        let public_key = "\
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8Thxn/QPBtw+tmuWH5xE
VxJYykWePThFg49EhpNrYZvJVSyCc2bD7CcnoE7R224hQyt5FKz2QBBoNFbR6b5T
FRaCw6Yv2sKc+8SpsMBQnDlBHvrXRt0jOmc5JTKk91UwBhWALeawsGOQMl+VVvUZ
W34dtJMjQ+ja/WGc5Nw8ZfUfhkLkTovkj/jocheDQfiwH0e+fj6p5n3/H2yVG7vQ
nBYRYW+F35pItlrcnU60+1zDnAKAGBdV+94AE7hx/zjIfq8+bYyrh0WgnhfKPllu
Wg581kaa1oXuBi/CEICOXnbRp75+J5sCybOkHpfdYr0+5iAtC7OkLA4DVPlt6d2A
0QIDAQAB
-----END PUBLIC KEY-----";
        let data = "Hello World";

        rsa_base64_encrypt(public_key, data)?;

        Ok(())
    }
}
