use dat::error::DatError;
use dat::sign::SignAlgorithm::{P256, P384, P521};
use dat::sign::{SignAlgorithm, SignKey};
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 sign_and_verify(alg: SignAlgorithm) -> Result<(), DatError> {
    let tag = format!("sign.{}", alg.to_str());
    let key = SignKey::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 = SignKey::from_bytes(alg, decode_base64_url_no_pad(b64_key)?.as_slice())?;
    let rand_string = rand_string();
    println!("{tag} rand_string {}", rand_string);
    let sign = encode_base64_url_no_pad(key.sign(rand_string.as_bytes()));
    let verify = parse_key.to_verify_key().verify(rand_string.as_bytes(), decode_base64_url_no_pad(sign)?.as_slice()).is_ok();
    assert!(verify);
    let un_verify = parse_key.to_verify_key().verify(rand_string.as_bytes(), &*SignKey::generate(alg).sign(rand_string.as_bytes())).is_ok();
    println!("{tag} verify {} / unverify {}", verify, un_verify);
    assert!(!un_verify);
    Ok(())
}

#[test]
fn test() {
    let alg_arr = [P256, P384, P521];
    alg_arr.iter().for_each(|alg| {
        (1..20).for_each(|_| {
            assert!(sign_and_verify(*alg).is_ok())
        });
    })
}