use bt_data::{SqliteMetadataStore, SymbolMapping};
use bt_kernel::{AssetClass, SymbolId, SymbolInfo, Timestamp};

#[test]
fn symbol_registry_roundtrip_and_mapping_resolution() {
    let store = SqliteMetadataStore::in_memory().expect("create in-memory metadata store");
    let symbol = SymbolInfo {
        id: SymbolId(42),
        ticker: "BTCUSDT".to_string(),
        asset_class: AssetClass::CryptoSpot,
        exchange: "BINANCE".to_string(),
        base_currency: "BTC".to_string(),
        quote_currency: "USDT".to_string(),
        tick_size: 0.01,
        lot_size: 0.0001,
        margin_required: None,
    };

    store
        .upsert_symbol(&symbol, None, None, serde_json::json!({"source": "test"}))
        .expect("upsert symbol");

    let valid_from = Timestamp(1_704_067_200_000_000_000);
    store
        .add_symbol_mapping(&SymbolMapping {
            provider: "binance".to_string(),
            raw_symbol: "BTCUSDT".to_string(),
            symbol_id: symbol.id,
            valid_from,
            valid_to: None,
        })
        .expect("insert symbol mapping");

    let resolved = store
        .resolve_symbol_mapping("binance", "BTCUSDT", Timestamp(valid_from.0 + 1))
        .expect("resolve mapping");
    assert_eq!(resolved, SymbolId(42));

    let loaded = store.symbol_info(SymbolId(42)).expect("read symbol info");
    assert_eq!(loaded.ticker, "BTCUSDT");
    assert_eq!(loaded.asset_class, AssetClass::CryptoSpot);

    let all_symbols = store.list_symbol_infos().expect("list symbols");
    assert_eq!(all_symbols.len(), 1);
    assert_eq!(all_symbols[0].id, SymbolId(42));
}

#[test]
fn mapping_valid_to_is_respected() {
    let store = SqliteMetadataStore::in_memory().expect("create in-memory metadata store");
    let symbol = SymbolInfo {
        id: SymbolId(1),
        ticker: "ETHUSDT".to_string(),
        asset_class: AssetClass::CryptoSpot,
        exchange: "BINANCE".to_string(),
        base_currency: "ETH".to_string(),
        quote_currency: "USDT".to_string(),
        tick_size: 0.01,
        lot_size: 0.0001,
        margin_required: None,
    };

    store
        .upsert_symbol(&symbol, None, None, serde_json::json!({}))
        .expect("upsert symbol");

    let valid_from = Timestamp(1_704_067_200_000_000_000);
    let valid_to = Timestamp(1_704_067_201_000_000_000);
    store
        .add_symbol_mapping(&SymbolMapping {
            provider: "binance".to_string(),
            raw_symbol: "ETHUSDT".to_string(),
            symbol_id: symbol.id,
            valid_from,
            valid_to: Some(valid_to),
        })
        .expect("insert mapping");

    assert!(store
        .resolve_symbol_mapping("binance", "ETHUSDT", Timestamp(valid_to.0 + 1))
        .is_err());
}
