use dat::crypt::CryptAlgorithm::{AES128GCMN, AES256GCMN};
use dat::crypt::{CryptAlgorithm, CryptKey};
use dat::error::DatError;
use dat::util::{decode_base64_url_no_pad, encode_base64_url_no_pad};
use rand::RngExt;

fn rand_string() -> String {
    let mut rng = rand::rng();
    (0..100).map(|_| { rng.sample(rand::distr::Alphanumeric) as char }).collect()
}
fn encrypt_and_decrypt(alg: CryptAlgorithm, rand_string: String) -> Result<(), DatError> {
    let tag = format!("crypt.{}", alg.to_str());
    println!("{tag} ready");
    let key = CryptKey::generate(alg);
    let byte_key = key.to_bytes();
    let b64_key = encode_base64_url_no_pad(&byte_key);
    println!("{tag} key {}", &b64_key);
    let parse_key = CryptKey::from_bytes(alg, decode_base64_url_no_pad(b64_key)?.as_slice())?;
    let rand_bytes = rand_string.as_bytes();
    println!("{tag} rand_string {}", rand_string);
    let encrypt = encode_base64_url_no_pad(key.to_cipher().encrypt(rand_bytes)?);
    let decrypt = parse_key.to_cipher().decrypt(decode_base64_url_no_pad(encrypt.clone())?.as_slice())?;
    let pass_decrypt = rand_bytes == decrypt;
    assert!(pass_decrypt);
    let fail_decrypt = CryptKey::generate(alg).to_cipher().decrypt(decode_base64_url_no_pad(encrypt)?.as_slice()).is_ok();
    assert!(!fail_decrypt || rand_string.is_empty());
    println!("{tag} pass {} / fail {}", pass_decrypt, fail_decrypt);
    Ok(())
}

#[test]
fn test() {
    let alg_arr = [AES128GCMN, AES256GCMN];
    alg_arr.iter().for_each(|alg| {
        // random
        (1..20).for_each(|_| {
            assert!(encrypt_and_decrypt(*alg, rand_string()).is_ok())
        });
        // empty
        assert!(encrypt_and_decrypt(*alg, "".to_string()).is_ok())
    })
}