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

/// Valor total do pedido
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct TotalAmount(f64);

impl TotalAmount {
    /// Cria um novo valor total validado
    pub fn new(value: f64) -> Result<Self, ValidationError> {
        if !value.is_finite() {
            return Err(ValidationError::InvalidFormat {
                field: "total_amount".to_string(),
                message: "total amount must be a finite number".to_string(),
            });
        }

        if value <= 0.0 {
            return Err(ValidationError::InvalidFormat {
                field: "total_amount".to_string(),
                message: format!("total amount must be positive, received: {}", value),
            });
        }

        Ok(Self(value))
    }

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

    /// Formata o valor em reais brasileiros
    pub fn format_brl(&self) -> String {
        format!("R$ {:.2}", self.0)
    }
}

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

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

    #[test]
    fn test_total_amount_valid() {
        let amount = TotalAmount::new(100.00).unwrap();
        assert_eq!(amount.value(), 100.00);
    }

    #[test]
    fn test_total_amount_zero() {
        let result = TotalAmount::new(0.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_total_amount_negative() {
        let result = TotalAmount::new(-10.0);
        assert!(result.is_err());
    }

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

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

    #[test]
    fn test_total_amount_format() {
        let amount = TotalAmount::new(1234.56).unwrap();
        assert_eq!(amount.format_brl(), "R$ 1234.56");
    }
}

