//! Dashboard API handlers.

use axum::{Json, extract::State};
use chattyness_error::AppError;
use serde::Serialize;
use sqlx::PgPool;

/// Dashboard stats response.
#[derive(Debug, Serialize)]
pub struct DashboardStats {
    pub total_users: i64,
    pub active_users: i64,
    pub total_realms: i64,
    pub online_users: i64,
    pub staff_count: i64,
}

/// Get dashboard stats.
pub async fn get_stats(State(pool): State<PgPool>) -> Result<Json<DashboardStats>, AppError> {
    // Total users
    let total_users: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM auth.users")
        .fetch_one(&pool)
        .await?;

    // Active users
    let active_users: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM auth.users WHERE status = 'active'")
            .fetch_one(&pool)
            .await?;

    // Total realms
    let total_realms: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM realm.realms")
        .fetch_one(&pool)
        .await?;

    // Staff count
    let staff_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM server.staff")
        .fetch_one(&pool)
        .await?;

    // Online users would require presence tracking - hardcoded to 0 for now
    let online_users = 0;

    Ok(Json(DashboardStats {
        total_users,
        active_users,
        total_realms,
        online_users,
        staff_count,
    }))
}
