use dat::error::DatError;
use dat::signature::DatSignatureAlgorithm;
use dat::signature::DatSignatureAlgorithm::{P256, P384, P521};
use dat::signature::DatSignatureKey;
use dat::util::{decode_base64_url, encode_base64_url};
use rand::RngExt;

fn rand_string() -> String {
    let mut rng = rand::rng();
    (0..100).map(|_| { rng.sample(rand::distr::Alphanumeric) as char }).collect()
}
fn signing_and_verifying(alg: DatSignatureAlgorithm) -> Result<(), DatError> {
    let tag = format!("signature.{}", alg);
    let key = DatSignatureKey::generate(alg)?;
    let (s, v) = key.to_bytes();
    let b64_s_key = encode_base64_url(&s);
    let b64_v_key = encode_base64_url(&v);
    let parse_key = DatSignatureKey::from_bytes(alg, &*decode_base64_url(b64_s_key)?, &*decode_base64_url(b64_v_key)?)?;
    let rand_string = rand_string();
    let sign = encode_base64_url(key.sign(rand_string.as_bytes())?);
    let verify = parse_key.verify(rand_string.as_bytes(), &*decode_base64_url(sign)?).is_ok();
    assert!(verify);
    let un_verify = parse_key.verify(rand_string.as_bytes(), &*DatSignatureKey::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!(signing_and_verifying(*alg).is_ok())
        });
    })
}