use serde::{Deserialize, Deserializer, Serialize};

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Debug, Default, Clone, Copy, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum InvoiceType {
    #[default]
    Income,
    Outcome,
}

impl<'de> Deserialize<'de> for InvoiceType {
    /// Tolerant deserializer. Accepts:
    /// - canonical lowercase variants `income` / `outcome` (case-insensitive);
    /// - any other string (e.g. FA(3) `rodzajFaktury` values like `VAT`,
    ///   `KOR`, `ZAL` that some clients mistakenly place into this field) —
    ///   coerced to `Outcome`, since every FA(3) kind here represents an
    ///   outgoing self-issued invoice.
    ///
    /// This prevents a cryptic `unknown variant 'VAT'` 400 from blocking the
    /// whole request payload when only this discriminator is misrouted.
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let raw = <String as Deserialize>::deserialize(d)?;
        Ok(match raw.to_ascii_lowercase().as_str() {
            "income" => InvoiceType::Income,
            _ => InvoiceType::Outcome,
        })
    }
}
