use alloy::rpc::types::Filter;
use anyhow::Result;
use ethl::rpc::backfill::backfill;
use ethl::rpc::config::ProviderSettings;
use futures_util::pin_mut;
use futures_util::stream::StreamExt;
use std::collections::HashSet;

#[tokio::test]
#[ntest::timeout(10000)]
async fn test_backfill() -> Result<()> {
    let settings =
        ProviderSettings::http(option_env!("TEST_RPC_URL").unwrap_or("https://0xrpc.io/base"))?;
    let filter = Filter::new().from_block(34762687).to_block(34762688);
    let log_stream = backfill(&settings, &filter).await;
    pin_mut!(log_stream);
    let mut blocks: HashSet<u64> = HashSet::default();
    let mut all = vec![];
    while let Some(result) = log_stream.next().await {
        let (from, to, logs) = result?;
        for log in &logs {
            all.push(((log.block_number.unwrap() as u128) << 16) + log.log_index.unwrap() as u128);
        }
        blocks.insert(from);
        blocks.insert(to);
    }
    assert_eq!(blocks.len(), 2);
    assert!(blocks.contains(&34762687));
    assert!(blocks.contains(&34762688));
    let mut sorted = all.clone();
    sorted.sort();
    assert_eq!(all, sorted);
    Ok(())
}
