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

/// Valor dos impostos
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct TaxAmount(f64);

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

        if value < 0.0 {
            return Err(ValidationError::InvalidFormat {
                field: "tax_amount".to_string(),
                message: format!("tax amount cannot be negative, 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 TaxAmount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:.2}", self.0)
    }
}

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

    #[test]
    fn test_tax_amount_valid() {
        let amount = TaxAmount::new(3.45).unwrap();
        assert_eq!(amount.value(), 3.45);
    }

    #[test]
    fn test_tax_amount_zero() {
        let amount = TaxAmount::new(0.0).unwrap();
        assert_eq!(amount.value(), 0.0);
    }

    #[test]
    fn test_tax_amount_negative() {
        let result = TaxAmount::new(-5.0);
        assert!(result.is_err());
    }

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

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

