// 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 Sha512Sum(#[serde_as(as = "serde_with::hex::Hex")] [u8; 64]);

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

    use super::Sha512Sum;

    fn example_sha512_sum() -> Sha512Sum {
        Sha512Sum([
            0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d,
            0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21,
            0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83,
            0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81,
            0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e,
        ])
    }

    fn example_sha512_sum_json() -> serde_json::Value {
        json!(
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
        )
    }

    #[test]
    fn serialize() {
        assert_eq!(json!(example_sha512_sum()), example_sha512_sum_json());
    }

    #[test]
    fn deserialize_good() {
        let deserialized: Sha512Sum = serde_json::from_value(example_sha512_sum_json())
            .expect("value must be deserializable as sha512sum");
        assert_eq!(deserialized, example_sha512_sum());
    }

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