use uuid::Uuid;
use crate::error::{CommonResult as Result, CommonError as Error};

/// Generate a new UUID v4
pub fn generate_uuid() -> Uuid {
    Uuid::new_v4()
}

/// Generate a random string of specified length
pub fn generate_random_string(length: usize) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    use std::time::{SystemTime, UNIX_EPOCH};
    
    let mut hasher = DefaultHasher::new();
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos().hash(&mut hasher);
    let hash = hasher.finish();
    
    format!("{:x}", hash)[..length.min(16)].to_string()
}

/// Generate a secure random token
pub fn generate_token(length: usize) -> Result<String> {
    use rand::Rng;
    
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let mut rng = rand::thread_rng();
    
    let token: String = (0..length)
        .map(|_| {
            let idx = rng.gen_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect();
    
    Ok(token)
}

/// Generate request ID
pub fn generate_request_id() -> String {
    format!("req_{}", generate_uuid())
}

/// Generate correlation ID
pub fn generate_correlation_id() -> String {
    format!("corr_{}", generate_uuid())
}
