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

#[serde_with::serde_as]
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    derive_more::AsRef,
    derive_more::From,
    derive_more::Into,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct Sha1Sum(#[serde_as(as = "serde_with::hex::Hex")] [u8; 20]);

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

    use super::Sha1Sum;

    fn example_sha1_sum() -> Sha1Sum {
        Sha1Sum([
            0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60,
            0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09,
        ])
    }

    fn example_sha1_sum_json() -> serde_json::Value {
        json!("da39a3ee5e6b4b0d3255bfef95601890afd80709")
    }

    #[test]
    fn serialize() {
        assert_eq!(json!(example_sha1_sum()), example_sha1_sum_json());
    }

    #[test]
    fn deserialize_good() {
        let deserialized: Sha1Sum = serde_json::from_value(example_sha1_sum_json())
            .expect("value must be deserializable as sha1sum");
        assert_eq!(deserialized, example_sha1_sum());
    }

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