#include "server/api_server.hpp"

#include "util/http_util.hpp"

namespace lm {

void ApiServer::registerPathRoutes(httplib::Server& svr)
{
  svr.Get("/api/paths", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string site_id = req.has_param("site_id") ? req.get_param_value("site_id") : "";
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = nlohmann::json({{"paths", path_store_.list(site_id)}}).dump();
  });

  svr.Get(R"(/api/paths/([^/]+)$)", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string id = req.matches[1];
    const auto path = path_store_.find(id);
    if (!path)
      return HttpUtil::jsonError(res, 404, "path not found");
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = path->dump();
  });

  svr.Delete(R"(/api/paths/([^/]+)$)", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string id = req.matches[1];
    std::string err;
    if (!path_store_.remove(id, err))
      return HttpUtil::jsonError(res, 404, err);
    res.status = 204;
  });
}

}  // namespace lm
