#include "server/api_server.hpp"

#include "auth/auth_service.hpp"
#include "util/http_util.hpp"

namespace lm {

void ApiServer::registerPathGuideRoutes(httplib::Server& svr)
{
  svr.Get("/api/path_guides", [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({{"path_guides", path_guide_store_.list(site_id)}}).dump();
  });

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

  svr.Post("/api/path_guides", [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");
    }
    if (const AuthSession* session = AuthService::activeSession())
    {
      if (!body.contains("created_by") || !body["created_by"].is_string() ||
          body["created_by"].get<std::string>().empty())
      {
        body["created_by"] = session->group_name.empty() ? session->username : session->group_name;
      }
      if (!body.contains("created_by_group") || !body["created_by_group"].is_string() ||
          body["created_by_group"].get<std::string>().empty())
        body["created_by_group"] = session->group_id;
    }
    std::string err;
    const auto created = path_guide_store_.create(body, err);
    if (!created)
      return HttpUtil::jsonError(res, 400, err);
    res.status = 201;
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = created->dump();
  });

  svr.Put(R"(/api/path_guides/([^/]+)$)", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string id = req.matches[1];
    nlohmann::json body;
    try
    {
      body = nlohmann::json::parse(req.body);
    }
    catch (...)
    {
      return HttpUtil::jsonError(res, 400, "invalid JSON");
    }
    std::string err;
    if (!path_guide_store_.update(id, body, err))
      return HttpUtil::jsonError(res, 400, err);
    const auto updated = path_guide_store_.find(id);
    res.set_header("Content-Type", "application/json; charset=utf-8");
    res.body = updated ? updated->dump() : nlohmann::json::object().dump();
  });

  svr.Delete(R"(/api/path_guides/([^/]+)$)", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string id = req.matches[1];
    const auto existing = path_guide_store_.find(id);
    if (!existing)
      return HttpUtil::jsonError(res, 404, "path guide not found");
    if (const AuthSession* session = AuthService::activeSession())
    {
      if (!AuthService::canDeleteMap(*existing, *session))
        return HttpUtil::jsonError(res, 403, "cannot delete path guide from another user group");
    }
    std::string err;
    if (!path_guide_store_.remove(id, err))
      return HttpUtil::jsonError(res, 400, err);
    res.status = 204;
  });
}

}  // namespace lm
