#include "server/api_server.hpp"

#include "util/http_util.hpp"

namespace lm {

void ApiServer::registerDashboardRoutes(httplib::Server& svr)
{
  svr.Get("/api/dashboards", [this](const httplib::Request&, httplib::Response& res) {
    HttpUtil::addCors(res);
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = dashboard_store_.snapshot().dump();
  });

  svr.Put("/api/dashboards", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    nlohmann::json body;
    try
    {
      body = nlohmann::json::parse(req.body);
    }
    catch (...)
    {
      return HttpUtil::jsonError(res, 400, "invalid JSON");
    }
    std::string err;
    if (!dashboard_store_.replace(body, err))
      return HttpUtil::jsonError(res, 400, err);
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = dashboard_store_.snapshot().dump();
  });
}

}  // namespace lm
