//! Admin-facing read helpers for client-pressure routes.

use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPool;

use crate::store::{
    ClientPressureBackfillRequestRecord, ClientPressureSnapshotRecord,
    ClientPressureSnapshotRunRecord, ClientTablePressureSnapshotRecord,
    enqueue_client_pressure_backfill_request, get_latest_client_pressure_detail,
    get_latest_client_pressure_run, list_latest_client_pressure_summaries,
    list_recent_client_pressure_history,
};

#[derive(Debug, Clone, Deserialize)]
pub struct ClientPressureBackfillRequest {
    #[serde(default)]
    pub hours_back: Option<i32>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ClientPressureOverview {
    pub snapshots: Vec<ClientPressureSnapshotRecord>,
    pub last_run: Option<ClientPressureSnapshotRunRecord>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ClientPressureDetailView {
    pub snapshot: ClientPressureSnapshotRecord,
    pub tables: Vec<ClientTablePressureSnapshotRecord>,
    pub history: Vec<ClientPressureSnapshotRecord>,
    pub last_run: Option<ClientPressureSnapshotRunRecord>,
}

pub fn normalize_backfill_hours(hours_back: Option<i32>) -> i32 {
    hours_back.unwrap_or(24).clamp(1, 24 * 30)
}

pub async fn queue_client_pressure_backfill_request(
    pool: &PgPool,
    hours_back: Option<i32>,
) -> Result<ClientPressureBackfillRequestRecord, sqlx::Error> {
    enqueue_client_pressure_backfill_request(pool, normalize_backfill_hours(hours_back)).await
}

pub async fn load_client_pressure_overview(
    pool: &PgPool,
) -> Result<ClientPressureOverview, sqlx::Error> {
    Ok(ClientPressureOverview {
        snapshots: list_latest_client_pressure_summaries(pool).await?,
        last_run: get_latest_client_pressure_run(pool).await?,
    })
}

pub async fn load_client_pressure_detail_view(
    pool: &PgPool,
    client_name: &str,
    history_limit: i64,
) -> Result<Option<ClientPressureDetailView>, sqlx::Error> {
    let Some((snapshot, tables)) = get_latest_client_pressure_detail(pool, client_name).await?
    else {
        return Ok(None);
    };

    Ok(Some(ClientPressureDetailView {
        snapshot,
        tables,
        history: list_recent_client_pressure_history(pool, client_name, history_limit).await?,
        last_run: get_latest_client_pressure_run(pool).await?,
    }))
}
