// prose-pod-api
//
// Copyright: 2025, Rémi Bardon <remi@remibardon.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

use serdev::{Deserialize, Deserializer};

/// Any value that is present is considered `Some` value, including `null`.
///
/// Copyright: [Treat null and missing field as being different · Issue #984 · serde-rs/serde](https://github.com/serde-rs/serde/issues/984#issuecomment-314143738).
pub fn deserialize_null_as_some_none<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
    T: Deserialize<'de>,
    D: Deserializer<'de>,
{
    Deserialize::deserialize(deserializer).map(Some)
}

pub mod prose_role_as_prosody {
    use serdev::de::{self};

    use crate::{members::MemberRole, prosody::ProsodyRoleName};

    use super::*;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<MemberRole, D::Error>
    where
        D: Deserializer<'de>,
    {
        let prosody_role = ProsodyRoleName::deserialize(deserializer)?;
        match MemberRole::try_from(&prosody_role) {
            Ok(role) => Ok(role),
            Err(err) => Err(de::Error::custom(err)),
        }
    }
}
