// SPDX-FileCopyrightText: Politik im Blick developers
// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
//
// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2

use std::{fmt::Display, str::FromStr};

use time::OffsetDateTime;

use crate::DateTime;

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    derive_more::AsRef,
    derive_more::From,
    derive_more::Into,
    serde_with::SerializeDisplay,
    serde_with::DeserializeFromStr,
)]
#[cfg_attr(feature = "sea-orm", derive(sea_orm::DeriveValueType))]
pub struct Date(time::Date);

impl FromStr for Date {
    type Err = time::error::Parse;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use time::format_description::well_known::Iso8601;

        Ok(Self(time::Date::parse(s, &Iso8601::DEFAULT)?))
    }
}

impl Display for Date {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use time::format_description::well_known::Iso8601;

        write!(f, "{}", self.0.format(&Iso8601::DATE).expect("valid date"))
    }
}

impl From<DateTime> for Date {
    fn from(value: DateTime) -> Self {
        Self(OffsetDateTime::from(value).date())
    }
}

#[cfg(test)]
mod tests {
    use time::macros::date;

    use super::Date;

    #[test]
    fn from_str() {
        let parsed: Date = "2025-01-07"
            .parse()
            .expect("string must be parseable as Date");
        assert_eq!(parsed, Date(date!(2025 - 01 - 07)));
    }

    #[test]
    fn to_string() {
        let d = Date(date!(2025 - 01 - 07));

        assert_eq!(d.to_string(), "2025-01-07".to_string());
    }
}

#[cfg(test)]
mod serde_tests {
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use time::macros::date;

    use super::Date;

    #[test]
    fn serialize() {
        assert_eq!(json!(Date(date!(2025 - 01 - 07))), json!("2025-01-07"));
    }

    #[test]
    fn deserialize_good() {
        let deserialized: Date =
            serde_json::from_value(json!("2025-01-07")).expect("json must be parseable as Date");

        assert_eq!(deserialized, Date(date!(2025 - 01 - 07)));
    }

    #[test]
    fn deserialize_bad() {
        assert!(serde_json::from_value::<Date>(json!("xyzabcd")).is_err());
        assert!(serde_json::from_value::<Date>(json!(true)).is_err());
        assert!(serde_json::from_value::<Date>(json!(123)).is_err());
    }
}
