use crate::types::validation_errors::ValidationError;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhoneNumber(String);

impl PhoneNumber {
    /// Cria um novo número de telefone
    pub fn new(phone: impl Into<String>) -> Result<Self, ValidationError> {
        let phone = phone.into();

        if phone.is_empty() {
            return Err(ValidationError::EmptyField("phone".to_string()));
        }

        if phone.len() > 100 {
            return Err(ValidationError::TooLong {
                field: "phone".to_string(),
                max: 100,
                actual: phone.len(),
            });
        }

        Ok(Self(phone))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Serialize for PhoneNumber {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for PhoneNumber {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        PhoneNumber::new(s).map_err(serde::de::Error::custom)
    }
}
