use crate::impl_nutype_error_conversion;
use nutype::nutype;

/// Nome do destinatário (máximo 100 caracteres)
///
/// # Validações
/// - Não pode ser vazio (após trim)
/// - Máximo 100 caracteres
///
/// # Exemplos
/// ```
/// use konduto::AddressName;
///
/// let name = AddressName::try_new("John Doe").unwrap();
/// assert_eq!(name.as_str(), "John Doe");
/// ```
#[nutype(
    sanitize(trim),
    validate(not_empty, len_char_max = 100),
    derive(
        Debug,
        Clone,
        PartialEq,
        Eq,
        Display,
        AsRef,
        Deref,
        Serialize,
        Deserialize,
    )
)]
pub struct AddressName(String);

impl AddressName {
    /// Retorna o nome como string slice (compatibilidade)
    pub fn as_str(&self) -> &str {
        self.as_ref()
    }
}

impl_nutype_error_conversion!(AddressNameError);

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

    #[test]
    fn test_valid_name() {
        let name = AddressName::try_new("John Doe").unwrap();
        assert_eq!(name.as_str(), "John Doe");
    }

    #[test]
    fn test_name_with_whitespace() {
        let name = AddressName::try_new("  John Doe  ").unwrap();
        assert_eq!(name.as_str(), "John Doe");
    }

    #[test]
    fn test_empty_name() {
        let result = AddressName::try_new("");
        assert!(result.is_err());
    }

    #[test]
    fn test_name_too_long() {
        let long_name = "a".repeat(101);
        let result = AddressName::try_new(long_name);
        assert!(result.is_err());
    }

    #[test]
    fn test_name_max_length() {
        let name = "a".repeat(100);
        let result = AddressName::try_new(name);
        assert!(result.is_ok());
    }

    #[test]
    fn test_serialization() {
        let name = AddressName::try_new("Jane Doe").unwrap();
        let json = serde_json::to_string(&name).unwrap();
        assert_eq!(json, "\"Jane Doe\"");
    }

    #[test]
    fn test_deserialization() {
        let json = "\"John Smith\"";
        let name: AddressName = serde_json::from_str(json).unwrap();
        assert_eq!(name.as_str(), "John Smith");
    }
}
