#include "csp/controllers/leaderboard_controller.h" #include "csp/app_state.h" #include "csp/domain/json.h" #include "csp/services/user_service.h" #include #include #include namespace csp::controllers { namespace { drogon::HttpResponsePtr JsonError(drogon::HttpStatusCode code, const std::string& msg) { Json::Value j; j["ok"] = false; j["error"] = msg; auto resp = drogon::HttpResponse::newHttpJsonResponse(j); resp->setStatusCode(code); return resp; } drogon::HttpResponsePtr JsonOkArray(const Json::Value& arr) { Json::Value j; j["ok"] = true; j["data"] = arr; auto resp = drogon::HttpResponse::newHttpJsonResponse(j); resp->setStatusCode(drogon::k200OK); return resp; } } // namespace void LeaderboardController::global( const drogon::HttpRequestPtr& req, std::function&& cb) { try { int limit = 100; const auto limit_str = req->getParameter("limit"); if (!limit_str.empty()) { limit = std::max(1, std::min(500, std::stoi(limit_str))); } std::string scope = req->getParameter("scope"); if (scope.empty()) scope = "all"; if (scope != "all" && scope != "week" && scope != "today") { cb(JsonError(drogon::k400BadRequest, "invalid scope")); return; } services::UserService users(csp::AppState::Instance().db()); const auto rows = users.GlobalLeaderboard(limit, scope); Json::Value arr(Json::arrayValue); for (const auto& r : rows) arr.append(domain::ToJson(r)); cb(JsonOkArray(arr)); } catch (const std::exception& e) { cb(JsonError(drogon::k500InternalServerError, e.what())); } } } // namespace csp::controllers