use zeroize::Zeroize;

use crate::{Error, Result};

const NONCE_LEN: usize = 12;

/// Represents a cryptographic nonce used to encrypt database entries.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Zeroize)]
pub struct Nonce([u8; NONCE_LEN]);

impl Nonce {
    /// Represents the byte length.
    pub const LEN: usize = NONCE_LEN;
    /// Represents the maximum nonce value.
    pub const MAX: u128 = 0xffff_ffff_ffff_ffff_ffff_ffff;
    /// Represents the counter nonce initialization value.
    pub const COUNTER: [u8; Self::LEN] =
        [1u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8];

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

    /// Creates a new counter [Nonce].
    pub const fn counter() -> Self {
        Self(Self::COUNTER)
    }

    /// Creates a new random [Nonce].
    pub fn random() -> Nonce {
        let mut nonce = Self::new();
        rand::fill(nonce.0.as_mut());
        nonce
    }

    /// Attempts to convert a byte slice into a [Nonce].
    ///
    /// Returns an error if `nonce` is not the correct [length](Self::LEN).
    pub fn from_slice(nonce: &[u8]) -> Result<Self> {
        nonce
            .try_into()
            .map(Self)
            .map_err(|_| Error::io_crypto(format!("invalid nonce length: {}", nonce.len())))
    }

    /// Converts the [Nonce] to a ChaCha20Poly1305 nonce.
    pub fn as_nonce(&self) -> &chacha20::Nonce {
        chacha20::Nonce::from_slice(&self.0)
    }

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

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

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

    /// Converts the [Nonce] into a [`u128`].
    #[inline]
    fn as_u128(&self) -> u128 {
        let [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb] = self.0;
        u128::from_le_bytes([b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, 0, 0, 0, 0])
    }

    /// Sets the inner value from a [`u128`].
    #[inline]
    fn set_from_u128(&mut self, val: u128) -> Result<()> {
        val.to_le_bytes()
            .get(..Self::LEN)
            .ok_or(Error::io_crypto("invalid nonce copy"))
            .map(|b| self.0.copy_from_slice(b))
    }

    /// Increments the [Nonce] value.
    ///
    /// Returns an error if the counter overflows.
    pub fn increment(&mut self) -> Result<()> {
        let next_val = self.as_u128().saturating_add(1);
        if next_val > Self::MAX {
            Err(Error::io_crypto("nonce counter overflowed"))
        } else {
            self.set_from_u128(next_val)
        }
    }
}

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

impl From<Nonce> for chacha20::Nonce {
    fn from(val: Nonce) -> Self {
        Self::clone_from_slice(&val.0)
    }
}

impl<'n> From<&'n Nonce> for &'n chacha20::Nonce {
    fn from(val: &'n Nonce) -> Self {
        val.as_nonce()
    }
}

impl TryFrom<&[u8]> for Nonce {
    type Error = Error;

    fn try_from(val: &[u8]) -> Result<Self> {
        Self::from_slice(val)
    }
}

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

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

impl PartialOrd for Nonce {
    fn partial_cmp(&self, oth: &Self) -> Option<std::cmp::Ordering> {
        self.as_u128().partial_cmp(&oth.as_u128())
    }
}

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

    const RAND_NONCES: usize = 1024;

    #[test]
    fn test_nonce() {
        let mut nonces = Vec::with_capacity(RAND_NONCES);

        (0..RAND_NONCES).for_each(|_| {
            let nonce = Nonce::random();

            assert!(nonce != Nonce::new());
            assert_eq!(nonce.as_slice(), &nonce.0);

            // assert no duplicate nonce has been generated
            assert!(!nonces.contains(&nonce));

            nonces.push(nonce);
        });
    }
}
