use sha3::TurboShake256;
use sha3::digest::{ExtendableOutput, Update, XofReader};
use zeroize::Zeroize;

const KEY_LEN: usize = 32;

/// Represents a salt used for password-based key derivation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Zeroize)]
pub struct SessionKey([u8; KEY_LEN]);

impl SessionKey {
    /// Represents the byte length.
    pub const LEN: usize = KEY_LEN;

    /// Creates a new [SessionKey].
    pub const fn new() -> Self {
        Self([0u8; Self::LEN])
    }

    /// Creates a new random [SessionKey].
    pub fn random() -> Self {
        let mut key = SessionKey::new();

        let mut input = [0u8; Self::LEN * 2];
        rand::fill(input.as_mut());

        let mut hasher = TurboShake256::from_core(sha3::TurboShake256Core::new(3));

        hasher.update(input.as_ref());

        let mut reader = hasher.finalize_xof();
        reader.read(key.as_mut());

        key
    }

    /// Converts a slice into a [SessionKey].
    pub fn from_slice(val: &[u8]) -> Self {
        let mut key = SessionKey::new();
        let len = std::cmp::min(Self::LEN, val.len());
        key.0[..len].copy_from_slice(&val[..len]);
        key
    }

    /// Gets a reference to the inner slice.
    pub const fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// Gets the [SessionKey] length.
    pub const fn len(&self) -> usize {
        Self::LEN
    }

    /// Gets whether the [SessionKey] is all zeroes.
    pub fn is_empty(&self) -> bool {
        self.0 == [0u8; Self::LEN]
    }
}

impl Default for SessionKey {
    fn default() -> Self {
        Self::new()
    }
}

impl AsRef<[u8]> for SessionKey {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl AsMut<[u8]> for SessionKey {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut()
    }
}

impl From<&[u8]> for SessionKey {
    fn from(val: &[u8]) -> Self {
        Self::from_slice(val)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const RAND_KEYS: usize = 1024;

    #[test]
    fn test_password() {
        let mut keys = Vec::with_capacity(RAND_KEYS);

        (0..RAND_KEYS).for_each(|_| {
            let key = SessionKey::random();

            assert!(key != SessionKey::new());
            assert!(!key.is_empty());

            // check the random salt creates unique password hashes
            assert!(!keys.contains(&key));

            keys.push(key);
        });
    }
}
