use anyhow::{Context, Result};
use base32::{Alphabet, encode};
use rand::{TryRng, rngs::SysRng};
use sha2::{Digest, Sha256};

pub fn create_secure_token() -> Result<(String, Vec<u8>)> {
    let mut random_bytes = [0u8; 16];
    // OsRng.fill_bytes(&mut random_bytes);

    SysRng
        .try_fill_bytes(&mut random_bytes)
        .context("Failed to fill bytes")?;

    // Use RFC4648 alphabet, no padding
    let plaintext = encode(Alphabet::Rfc4648 { padding: false }, &random_bytes);

    let hash = create_hash_from_plaintext(&plaintext);

    Ok((plaintext, hash))
}

pub fn create_hash_from_plaintext(plaintext: &str) -> Vec<u8> {
    let mut hasher = Sha256::new();
    hasher.update(plaintext.as_bytes());
    hasher.finalize().to_vec()
}
