// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.
use serde::{Deserialize, Deserializer, Serialize};

/// A single item in an array of arbitrary values, which can be a string, number, object, or boolean.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(untagged)]
pub enum AnyValueItem {
    AnyValueString(String),
    AnyValueNumber(f64),
    AnyValueObject(std::collections::BTreeMap<String, serde_json::Value>),
    AnyValueBoolean(bool),
    UnparsedObject(crate::datadog::UnparsedObject),
}

impl<'de> Deserialize<'de> for AnyValueItem {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value: serde_json::Value = Deserialize::deserialize(deserializer)?;
        if let Ok(_v) = serde_json::from_value::<String>(value.clone()) {
            return Ok(AnyValueItem::AnyValueString(_v));
        }
        if let Ok(_v) = serde_json::from_value::<f64>(value.clone()) {
            return Ok(AnyValueItem::AnyValueNumber(_v));
        }
        if let Ok(_v) = serde_json::from_value::<
            std::collections::BTreeMap<String, serde_json::Value>,
        >(value.clone())
        {
            return Ok(AnyValueItem::AnyValueObject(_v));
        }
        if let Ok(_v) = serde_json::from_value::<bool>(value.clone()) {
            return Ok(AnyValueItem::AnyValueBoolean(_v));
        }

        return Ok(AnyValueItem::UnparsedObject(
            crate::datadog::UnparsedObject { value },
        ));
    }
}
