// 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

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    derive_more::AsRef,
    derive_more::Display,
    derive_more::From,
    derive_more::FromStr,
    derive_more::Into,
    serde::Serialize,
    serde::Deserialize,
)]
#[cfg_attr(feature = "sea-orm", derive(sea_orm::DeriveValueType))]
pub struct Name(String);

impl From<&str> for Name {
    fn from(value: &str) -> Self {
        Self(value.into())
    }
}

impl Name {
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

#[cfg(feature = "sea-orm")]
mod sea_orm_impls {
    use sea_orm::{ActiveValue, IntoActiveValue};

    use super::Name;

    impl IntoActiveValue<Name> for Name {
        fn into_active_value(self) -> ActiveValue<Name> {
            ActiveValue::Set(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::Name;

    #[test]
    fn from_str() {
        assert_eq!(
            Name("Beispiel-System".to_string()),
            "Beispiel-System"
                .parse()
                .expect("value must be a parseable name")
        );
    }
}

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

    use super::Name;

    #[test]
    fn serialize() {
        assert_eq!(
            json!(Name("Beispiel-System".to_string())),
            json!("Beispiel-System")
        );
    }

    #[test]
    fn deserialize_good() {
        let deserialized: Name = serde_json::from_value(json!("Beispiel-System"))
            .expect("value must be deserializable as Name");
        assert_eq!(deserialized, Name::from("Beispiel-System"));
    }

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