#pragma once

#include <nlohmann/json.hpp>

#include <filesystem>
#include <mutex>
#include <optional>
#include <string>

namespace lm {

class Database;

class MapStore
{
public:
  MapStore(Database& db);

  nlohmann::json list() const;
  std::optional<nlohmann::json> find(const std::string& id) const;
  std::optional<nlohmann::json> create(const nlohmann::json& payload, std::string& err);
  bool update(const std::string& id, const nlohmann::json& payload, std::string& err);
  bool remove(const std::string& id, std::string& err);

  std::filesystem::path mapDir(const std::string& id) const;
  std::optional<std::filesystem::path> imagePath(const std::string& id) const;
  /** Scan/original floor plan (map_base.png); falls back to composite image if missing. */
  std::optional<std::filesystem::path> baseImagePath(const std::string& id) const;
  std::optional<std::filesystem::path> yamlPath(const std::string& id) const;
  bool saveImageFile(const std::string& id, const std::string& filename, const std::string& bytes, std::string& err);
  /** Save flattened composite (map.png) without touching map_base.png. */
  bool saveCompositeImageFile(const std::string& id, const std::string& bytes, std::string& err);
  /** Save base scan layer (map_base.png) only. */
  bool saveBaseImageFile(const std::string& id, const std::string& bytes, std::string& err);
  bool saveYamlFile(const std::string& id, const std::string& yaml_text, std::string& err);

private:
  Database& db_;
  mutable std::mutex mu_;
};

}  // namespace lm
