//! Sustained load test: 10,000 orders/sec for 60 seconds

use anyhow::Result;
use std::sync::Arc;
use tokio::task::JoinSet;

use crate::clients::TradingClient;
use crate::metrics::LoadTestMetrics;

pub async fn run(url: &str) -> Result<crate::metrics::LoadTestReport> {
    const _TARGET_RPS: usize = 10_000;
    const DURATION_SECS: u64 = 60;
    const CONCURRENT_CLIENTS: usize = 100;

    tracing::info!("Starting Sustained Load Test: 10,000 orders/sec for 60s");

    let metrics = Arc::new(LoadTestMetrics::new());
    let mut join_set = JoinSet::new();

    for client_id in 0..CONCURRENT_CLIENTS {
        let url = url.to_string();
        let metrics = Arc::clone(&metrics);

        join_set.spawn(async move {
            let mut client = TradingClient::connect(&url).await?;
            client
                .run_order_workload(client_id, DURATION_SECS, &metrics)
                .await
        });
    }

    // Memory monitoring
    let metrics_clone = Arc::clone(&metrics);
    let monitor = tokio::spawn(async move {
        crate::metrics::monitor_memory(DURATION_SECS, &metrics_clone).await;
    });

    // Wait for all clients
    while let Some(result) = join_set.join_next().await {
        if let Err(e) = result {
            tracing::error!("Client task failed: {:?}", e);
        }
    }

    monitor.abort();

    Ok(metrics.to_report("Sustained Load: 10,000 orders/sec"))
}
