#include "server/static_file_server.hpp"

#include "util/file_util.hpp"
#include "util/http_util.hpp"

namespace fs = std::filesystem;

namespace lm {

void StaticFileServer::mount(httplib::Server& svr, const fs::path& www_root)
{
  svr.Get(R"(/(.*))", [www_root](const httplib::Request& req, httplib::Response& res) {
    std::string rel = req.matches.size() >= 2 ? req.matches[1].str() : "";
    if (rel.empty())
      rel = "index.html";

    if (rel.find("..") != std::string::npos)
    {
      res.status = 400;
      res.set_content("Bad path", "text/plain; charset=utf-8");
      return;
    }

    fs::path file_path = www_root / rel;
    if (fs::is_directory(file_path))
      file_path /= "index.html";

    std::error_code ec;
    if (!fs::exists(file_path, ec) || ec)
    {
      res.status = 404;
      res.set_content("Not Found", "text/plain; charset=utf-8");
      return;
    }

    const auto body = FileUtil::readBinary(file_path);
    if (body.empty())
    {
      res.status = 500;
      res.set_content("Failed to read file", "text/plain; charset=utf-8");
      return;
    }

    res.set_header("Cache-Control", "no-store");
    res.set_content(body, HttpUtil::contentTypeForPath(file_path));
  });
}

}  // namespace lm
