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

/// Longitude da loja física (-180 a 180)
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct Longitude(f64);

impl Longitude {
    const MIN: f64 = -180.0;
    const MAX: f64 = 180.0;

    /// Cria uma nova longitude validada
    pub fn new(value: f64) -> Result<Self, ValidationError> {
        if !value.is_finite() {
            return Err(ValidationError::InvalidFormat {
                field: "longitude".to_string(),
                message: "longitude must be a finite number".to_string(),
            });
        }

        if !(Self::MIN..=Self::MAX).contains(&value) {
            return Err(ValidationError::InvalidFormat {
                field: "longitude".to_string(),
                message: format!(
                    "longitude must be between {} and {}, received: {}",
                    Self::MIN,
                    Self::MAX,
                    value
                ),
            });
        }

        Ok(Self(value))
    }

    pub fn value(&self) -> f64 {
        self.0
    }
}

impl fmt::Display for Longitude {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

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

    #[test]
    fn test_longitude_valid() {
        let lon = Longitude::new(-46.6487763).unwrap();
        assert_eq!(lon.value(), -46.6487763);
    }

    #[test]
    fn test_longitude_zero() {
        let lon = Longitude::new(0.0).unwrap();
        assert_eq!(lon.value(), 0.0);
    }

    #[test]
    fn test_longitude_min() {
        let lon = Longitude::new(-180.0).unwrap();
        assert_eq!(lon.value(), -180.0);
    }

    #[test]
    fn test_longitude_max() {
        let lon = Longitude::new(180.0).unwrap();
        assert_eq!(lon.value(), 180.0);
    }

    #[test]
    fn test_longitude_too_low() {
        let result = Longitude::new(-180.1);
        assert!(result.is_err());
    }

    #[test]
    fn test_longitude_too_high() {
        let result = Longitude::new(180.1);
        assert!(result.is_err());
    }

    #[test]
    fn test_longitude_nan() {
        let result = Longitude::new(f64::NAN);
        assert!(result.is_err());
    }

    #[test]
    fn test_longitude_infinity() {
        let result = Longitude::new(f64::INFINITY);
        assert!(result.is_err());
    }
}

