use std::sync::Arc;

use axum::{
    extract::State,
    routing::get,
    Json, Router,
};

use crate::db;
use crate::models::error::{ApiError, ApiResult};
use crate::models::public::StatusPageResponse;
use crate::AppState;

pub fn router() -> Router<Arc<AppState>> {
    Router::new()
        .route("/status", get(get_status_page))
        .route("/servers", get(list_public_servers))
        .route("/servers/{id}", get(get_public_server))
        .route("/servers/{id}/wipe-schedule", get(get_wipe_schedule))
        .route("/servers/{id}/countdown", get(get_countdown))
        .route("/servers/{id}/map", get(get_current_map))
        .route("/servers/{id}/players", get(get_players))
        .route("/servers/{id}/mods", get(get_mods))
        .route("/servers/{id}/motd", get(get_motd))
        .route("/servers/{id}/store", get(get_store))
}

/// GET /api/public/status — Public status page data (no auth required)
///
/// Returns all servers opted into the public status page with current stats,
/// plus platform-wide health metrics.
async fn get_status_page(
    State(state): State<Arc<AppState>>,
) -> ApiResult<Json<StatusPageResponse>> {
    let servers = db::public::get_public_servers(&state.db)
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to fetch servers: {}", e)))?;

    let platform_health = db::public::get_platform_health(&state.db)
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to fetch platform health: {}", e)))?;

    Ok(Json(StatusPageResponse {
        servers,
        platform_health,
    }))
}

async fn list_public_servers() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_public_server() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_wipe_schedule() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_countdown() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_current_map() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_players() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_mods() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_motd() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}

async fn get_store() -> ApiResult<Json<serde_json::Value>> {
    Ok(Json(serde_json::json!({"status": "not_implemented"})))
}
