use axum::{Json, extract::State};
use chrono::{DateTime, Utc};
use serde::Serialize;

use crate::error::ApiError;
use crate::state::AppState;
use swym_dal::repo::ingestion_stats;

#[derive(Debug, Serialize)]
pub struct InstrumentStatsResponse {
    pub instrument_id: i32,
    pub exchange_name: String,
    pub base_asset: String,
    pub quote_asset: String,
    pub kind: String,
    pub trade_count_total: i64,
    pub trade_count_1h: i64,
    pub l1_count_total: i64,
    pub l1_count_1h: i64,
    pub latest_trade_time: Option<DateTime<Utc>>,
    pub latest_l1_time: Option<DateTime<Utc>>,
    pub estimated_storage_bytes: i64,
}

/// GET /api/v1/ingestion-stats
pub async fn get_ingestion_stats(
    State(state): State<AppState>,
) -> Result<Json<Vec<InstrumentStatsResponse>>, ApiError> {
    let rows = ingestion_stats::get_instrument_stats(&state.pool).await?;
    let responses: Vec<InstrumentStatsResponse> = rows
        .into_iter()
        .map(|r| InstrumentStatsResponse {
            instrument_id: r.instrument_id,
            exchange_name: r.exchange_name,
            base_asset: r.base_asset,
            quote_asset: r.quote_asset,
            kind: r.kind,
            trade_count_total: r.trade_count_total,
            trade_count_1h: r.trade_count_1h,
            l1_count_total: r.l1_count_total,
            l1_count_1h: r.l1_count_1h,
            latest_trade_time: r.latest_trade_time,
            latest_l1_time: r.latest_l1_time,
            estimated_storage_bytes: r.estimated_storage_bytes,
        })
        .collect();
    Ok(Json(responses))
}
