//! Peak burst test: 50,000 orders/sec for 10 seconds

use anyhow::Result;
use std::sync::Arc;
use tokio::sync::Barrier;
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 = 50_000;
    const DURATION_SECS: u64 = 10;
    const CONCURRENT_CLIENTS: usize = 500;

    tracing::info!("Starting Peak Burst Test: 50,000 orders/sec for 10s");

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

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

        join_set.spawn(async move {
            let mut client = TradingClient::connect(&url).await?;

            // Synchronized start for burst
            barrier.wait().await;

            client
                .run_burst_workload(client_id, DURATION_SECS, &metrics)
                .await
        });
    }

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

    Ok(metrics.to_report("Peak Burst: 50,000 orders/sec"))
}
