#include "server/api_server.hpp"

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

namespace lm {

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

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

  svr.Post("/api/transitions", [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;
      }
    }
    std::string err;
    const auto created = transition_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/transitions/([^/]+)$)", [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 (!transition_store_.update(id, body, err))
      return HttpUtil::jsonError(res, 404, err);
    const auto updated = transition_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/transitions/([^/]+)$)", [this](const httplib::Request& req, httplib::Response& res) {
    HttpUtil::addCors(res);
    const std::string id = req.matches[1];
    std::string err;
    if (!transition_store_.remove(id, err))
      return HttpUtil::jsonError(res, 404, err);
    res.status = 204;
  });
}

}  // namespace lm

