use anyhow::Error;
use culpa::throws;
use serde_json::Value;

mod common;

// This test ensures that the `system:transports_info` virtual collection maintains a stable
// interface. Since this collection is customer-facing, we need to be careful about breaking
// changes and new features.
#[throws]
#[tokio::test]
async fn test_transports_info_virtual_collection() {
    let ditto = common::get_builder_ditto(None)?;
    test_transports_info_virtual_collection_impl(ditto).await?;

    let ditto = common::get_revamp_ditto(None)?;
    test_transports_info_virtual_collection_impl(ditto).await?;
}

#[throws]
async fn test_transports_info_virtual_collection_impl(ditto: dittolive_ditto::prelude::Ditto) {
    ditto.disable_sync_with_v3()?;

    let query_result = ditto
        .store()
        .execute_v2("SELECT * from system:transports_info")
        .await?;

    // Currently there should only be 1 document in the `transports_info` virtual collection
    // { '_id': 'discovery_hint', 'value': 'Q2RMCGNjRQtAjFditto' }
    assert_eq!(query_result.item_count(), 1);

    let item = query_result
        .get_item(0)
        .unwrap()
        .deserialize_value::<Value>()?;

    let Value::Object(object) = item else {
        panic!("Document should be an object");
    };

    assert_eq!(
        object.get("_id"),
        Some(&Value::String("discovery_hint".to_owned()))
    );
    assert!(matches!(object.get("value"), Some(&Value::String(_))));
}
