#pragma once

#include <nlohmann/json.hpp>

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

namespace lm {

class Database;

class MissionStore
{
public:
  explicit MissionStore(Database& db);

  nlohmann::json snapshot() const;
  bool replace(const nlohmann::json& payload, std::string& err);

  nlohmann::json listMissions() const;
  std::optional<nlohmann::json> findMission(const std::string& id) const;

  nlohmann::json listTriggers() const;
  std::optional<nlohmann::json> addTrigger(const nlohmann::json& payload, std::string& err);
  bool deleteTrigger(const std::string& id, std::string& err);
  std::optional<nlohmann::json> findTriggerByCoil(int coil_id) const;

  nlohmann::json listSchedules() const;
  std::optional<nlohmann::json> addSchedule(const nlohmann::json& payload, std::string& err);
  bool updateSchedule(const std::string& id, const nlohmann::json& payload, std::string& err);
  bool deleteSchedule(const std::string& id, std::string& err);
  std::optional<nlohmann::json> findSchedule(const std::string& id) const;

  nlohmann::json listRobots() const;

private:
  Database& db_;
  mutable std::mutex mu_;
  nlohmann::json data_;

  void load();
  void saveUnlocked() const;
  void ensureSchemaUnlocked();
};

}  // namespace lm
