use crate::error::DalError;
use crate::models::ingestion_stats::InstrumentStatsRow;
use sqlx::PgPool;

/// Get per-instrument ingestion statistics: total/1h counts and latest timestamps
/// for both trades and L1 order book snapshots.
pub async fn get_instrument_stats(pool: &PgPool) -> Result<Vec<InstrumentStatsRow>, DalError> {
    let rows = sqlx::query_as::<_, InstrumentStatsRow>(
        "WITH table_avg AS (
             SELECT
                 COALESCE(
                     (SELECT (relpages::bigint * 8192) / NULLIF(reltuples::bigint, 0)
                      FROM pg_class WHERE relname = 'market_trades'),
                     100
                 ) AS trade_row_bytes,
                 COALESCE(
                     (SELECT (relpages::bigint * 8192) / NULLIF(reltuples::bigint, 0)
                      FROM pg_class WHERE relname = 'market_order_book_l1'),
                     120
                 ) AS l1_row_bytes
         )
         SELECT
             i.id AS instrument_id,
             e.name AS exchange_name,
             i.base_asset,
             i.quote_asset,
             i.kind,
             COALESCE(t.trade_count_total, 0) AS trade_count_total,
             COALESCE(t.trade_count_1h, 0) AS trade_count_1h,
             COALESCE(l.l1_count_total, 0) AS l1_count_total,
             COALESCE(l.l1_count_1h, 0) AS l1_count_1h,
             t.latest_trade_time,
             l.latest_l1_time,
             COALESCE(t.trade_count_total, 0) * ta.trade_row_bytes
               + COALESCE(l.l1_count_total, 0) * ta.l1_row_bytes AS estimated_storage_bytes
         FROM table_avg ta, instruments i
         JOIN exchanges e ON e.id = i.exchange_id
         LEFT JOIN LATERAL (
             SELECT
                 COUNT(*) AS trade_count_total,
                 COUNT(*) FILTER (WHERE mt.time_exchange >= now() - interval '1 hour') AS trade_count_1h,
                 MAX(mt.time_exchange) AS latest_trade_time
             FROM market_trades mt
             WHERE mt.instrument_id = i.id
         ) t ON true
         LEFT JOIN LATERAL (
             SELECT
                 COUNT(*) AS l1_count_total,
                 COUNT(*) FILTER (WHERE ob.time_exchange >= now() - interval '1 hour') AS l1_count_1h,
                 MAX(ob.time_exchange) AS latest_l1_time
             FROM market_order_book_l1 ob
             WHERE ob.instrument_id = i.id
         ) l ON true
         ORDER BY e.name, i.base_asset, i.quote_asset",
    )
    .fetch_all(pool)
    .await?;

    Ok(rows)
}
