use rand::distributions::Alphanumeric;
use rand::Rng;

use crate::hash::sha256_hex;

/// Prefix used to identify rok API keys in `Authorization: Bearer` headers.
pub const KEY_PREFIX: &str = "rk_live_";

/// Generate a raw API key string: `rk_live_` + 40 random alphanumeric chars.
///
/// The raw key is shown to the user once and never stored.  Hash it with
/// [`hash_key`] before persisting.
pub fn generate_key() -> String {
    let random: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(40)
        .map(char::from)
        .collect();
    format!("{KEY_PREFIX}{random}")
}

/// SHA-256 hash of a raw API key — use this value for DB storage.
pub fn hash_key(raw: &str) -> String {
    sha256_hex(raw)
}

/// Return `true` if `s` looks like a rok API key (starts with `rk_live_`).
pub fn is_api_key(s: &str) -> bool {
    s.starts_with(KEY_PREFIX)
}
