use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::Serialize;

use super::auth::AppState;
use super::helpers::internal_error;

#[derive(Serialize)]
pub(super) struct GlobalStatsResponse {
    #[serde(rename = "total_tokens_saved")]
    pub tokens_saved: i64,
    #[serde(rename = "total_users")]
    pub users: i64,
    #[serde(rename = "total_contributions")]
    pub contributions: i64,
    #[serde(rename = "total_teams")]
    pub teams: i64,
}

pub(super) async fn get_global_stats(
    State(state): State<AppState>,
) -> Result<Json<GlobalStatsResponse>, (StatusCode, String)> {
    let client = state.pool.get().await.map_err(internal_error)?;

    let tokens_saved: i64 = client
        .query_one(
            "SELECT COALESCE(SUM(total_tokens_saved), 0)::BIGINT FROM user_profiles",
            &[],
        )
        .await
        .map_err(internal_error)?
        .get(0);

    let users: i64 = client
        .query_one("SELECT COUNT(*) FROM users", &[])
        .await
        .map_err(internal_error)?
        .get(0);

    let contributions: i64 = client
        .query_one("SELECT COUNT(*) FROM contribute_entries", &[])
        .await
        .map_err(internal_error)?
        .get(0);

    Ok(Json(GlobalStatsResponse {
        tokens_saved,
        users,
        contributions,
        teams: 0,
    }))
}
