#include "storage/transition_store.hpp"

#include "storage/database.hpp"
#include "util/id_util.hpp"
#include "util/string_util.hpp"

#include <sqlite3.h>

namespace lm {

namespace {

nlohmann::json rowToJson(sqlite3_stmt* stmt)
{
  auto text = [&](int col) -> std::string {
    if (sqlite3_column_type(stmt, col) == SQLITE_NULL)
      return "";
    const char* v = reinterpret_cast<const char*>(sqlite3_column_text(stmt, col));
    return v ? std::string(v) : "";
  };
  return {{"id", text(0)},
          {"site_id", text(1)},
          {"from_map_id", text(2)},
          {"to_map_id", text(3)},
          {"start_position_id", text(4)},
          {"goal_position_id", text(5)},
          {"mission_id", text(6)},
          {"created_by", text(7)},
          {"created_at", text(8)},
          {"updated_at", text(9)}};
}

}  // namespace

TransitionStore::TransitionStore(Database& db) : db_(db) {}

nlohmann::json TransitionStore::list(const std::string& site_id) const
{
  std::lock_guard<std::mutex> lock(mu_);
  nlohmann::json out = nlohmann::json::array();
  std::string sql =
      "SELECT id, site_id, from_map_id, to_map_id, start_position_id, goal_position_id, mission_id, created_by, created_at, updated_at "
      "FROM transitions";
  if (!site_id.empty())
    sql += " WHERE site_id = ?1";
  sql += " ORDER BY site_id, from_map_id, to_map_id, created_at";

  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(), sql.c_str(), -1, &stmt, nullptr) != SQLITE_OK)
    return out;
  if (!site_id.empty())
    sqlite3_bind_text(stmt, 1, site_id.c_str(), -1, SQLITE_TRANSIENT);
  while (sqlite3_step(stmt) == SQLITE_ROW)
    out.push_back(rowToJson(stmt));
  sqlite3_finalize(stmt);
  return out;
}

std::optional<nlohmann::json> TransitionStore::findBetween(const std::string& from_map_id,
                                                            const std::string& to_map_id) const
{
  if (from_map_id.empty() || to_map_id.empty() || from_map_id == to_map_id)
    return std::nullopt;

  std::lock_guard<std::mutex> lock(mu_);
  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(),
                         "SELECT id, site_id, from_map_id, to_map_id, start_position_id, goal_position_id, mission_id, "
                         "created_by, created_at, updated_at FROM transitions WHERE from_map_id = ?1 AND to_map_id = ?2 LIMIT 1",
                         -1,
                         &stmt,
                         nullptr) != SQLITE_OK)
    return std::nullopt;
  sqlite3_bind_text(stmt, 1, from_map_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 2, to_map_id.c_str(), -1, SQLITE_TRANSIENT);
  std::optional<nlohmann::json> out;
  if (sqlite3_step(stmt) == SQLITE_ROW)
    out = rowToJson(stmt);
  sqlite3_finalize(stmt);
  return out;
}

std::optional<nlohmann::json> TransitionStore::find(const std::string& id) const
{
  std::lock_guard<std::mutex> lock(mu_);
  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(),
                         "SELECT id, site_id, from_map_id, to_map_id, start_position_id, goal_position_id, mission_id, "
                         "created_by, created_at, updated_at FROM transitions WHERE id = ?1",
                         -1,
                         &stmt,
                         nullptr) != SQLITE_OK)
    return std::nullopt;
  sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);
  std::optional<nlohmann::json> out;
  if (sqlite3_step(stmt) == SQLITE_ROW)
    out = rowToJson(stmt);
  sqlite3_finalize(stmt);
  return out;
}

std::optional<nlohmann::json> TransitionStore::create(const nlohmann::json& payload, std::string& err)
{
  if (!payload.is_object())
  {
    err = "payload must be an object";
    return std::nullopt;
  }
  const std::string site_id = StringUtil::trimCopy(payload.value("site_id", ""));
  const std::string from_map_id = StringUtil::trimCopy(payload.value("from_map_id", ""));
  const std::string to_map_id = StringUtil::trimCopy(payload.value("to_map_id", ""));
  const std::string start_position_id = StringUtil::trimCopy(payload.value("start_position_id", ""));
  const std::string goal_position_id = StringUtil::trimCopy(payload.value("goal_position_id", ""));
  const std::string mission_id = StringUtil::trimCopy(payload.value("mission_id", ""));
  const std::string created_by = StringUtil::trimCopy(payload.value("created_by", ""));
  if (site_id.empty() || from_map_id.empty() || to_map_id.empty() || start_position_id.empty() || goal_position_id.empty() ||
      mission_id.empty())
  {
    err = "missing required fields";
    return std::nullopt;
  }
  if (from_map_id == to_map_id)
  {
    err = "from_map_id and to_map_id must differ";
    return std::nullopt;
  }

  const std::string id = payload.value("id", IdUtil::newId());
  const std::string now = IdUtil::nowIso8601();

  std::lock_guard<std::mutex> lock(mu_);
  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(),
                         "INSERT INTO transitions(id, site_id, from_map_id, to_map_id, start_position_id, goal_position_id, "
                         "mission_id, created_by, created_at, updated_at) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)",
                         -1,
                         &stmt,
                         nullptr) != SQLITE_OK)
  {
    err = sqlite3_errmsg(db_.handle());
    return std::nullopt;
  }
  sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 2, site_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 3, from_map_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 4, to_map_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 5, start_position_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 6, goal_position_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 7, mission_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 8, created_by.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 9, now.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 10, now.c_str(), -1, SQLITE_TRANSIENT);
  if (sqlite3_step(stmt) != SQLITE_DONE)
  {
    err = sqlite3_errmsg(db_.handle());
    sqlite3_finalize(stmt);
    return std::nullopt;
  }
  sqlite3_finalize(stmt);
  return nlohmann::json{{"id", id},
                        {"site_id", site_id},
                        {"from_map_id", from_map_id},
                        {"to_map_id", to_map_id},
                        {"start_position_id", start_position_id},
                        {"goal_position_id", goal_position_id},
                        {"mission_id", mission_id},
                        {"created_by", created_by},
                        {"created_at", now},
                        {"updated_at", now}};
}

bool TransitionStore::update(const std::string& id, const nlohmann::json& payload, std::string& err)
{
  auto existing = find(id);
  if (!existing)
  {
    err = "transition not found";
    return false;
  }

  nlohmann::json merged = *existing;
  for (const char* key :
       {"site_id", "from_map_id", "to_map_id", "start_position_id", "goal_position_id", "mission_id"})
  {
    if (payload.contains(key))
      merged[key] = payload[key];
  }

  const std::string site_id = StringUtil::trimCopy(merged.value("site_id", ""));
  const std::string from_map_id = StringUtil::trimCopy(merged.value("from_map_id", ""));
  const std::string to_map_id = StringUtil::trimCopy(merged.value("to_map_id", ""));
  const std::string start_position_id = StringUtil::trimCopy(merged.value("start_position_id", ""));
  const std::string goal_position_id = StringUtil::trimCopy(merged.value("goal_position_id", ""));
  const std::string mission_id = StringUtil::trimCopy(merged.value("mission_id", ""));
  if (site_id.empty() || from_map_id.empty() || to_map_id.empty() || start_position_id.empty() || goal_position_id.empty() ||
      mission_id.empty())
  {
    err = "missing required fields";
    return false;
  }
  if (from_map_id == to_map_id)
  {
    err = "from_map_id and to_map_id must differ";
    return false;
  }

  const std::string now = IdUtil::nowIso8601();
  std::lock_guard<std::mutex> lock(mu_);
  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(),
                         "UPDATE transitions SET site_id=?2, from_map_id=?3, to_map_id=?4, start_position_id=?5, "
                         "goal_position_id=?6, mission_id=?7, updated_at=?8 WHERE id=?1",
                         -1,
                         &stmt,
                         nullptr) != SQLITE_OK)
  {
    err = sqlite3_errmsg(db_.handle());
    return false;
  }
  sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 2, site_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 3, from_map_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 4, to_map_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 5, start_position_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 6, goal_position_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 7, mission_id.c_str(), -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 8, now.c_str(), -1, SQLITE_TRANSIENT);
  const bool ok = sqlite3_step(stmt) == SQLITE_DONE;
  if (!ok)
    err = sqlite3_errmsg(db_.handle());
  sqlite3_finalize(stmt);
  return ok;
}

bool TransitionStore::remove(const std::string& id, std::string& err)
{
  if (!find(id))
  {
    err = "transition not found";
    return false;
  }
  std::lock_guard<std::mutex> lock(mu_);
  sqlite3_stmt* stmt = nullptr;
  if (sqlite3_prepare_v2(db_.handle(), "DELETE FROM transitions WHERE id = ?1", -1, &stmt, nullptr) != SQLITE_OK)
  {
    err = sqlite3_errmsg(db_.handle());
    return false;
  }
  sqlite3_bind_text(stmt, 1, id.c_str(), -1, SQLITE_TRANSIENT);
  const bool ok = sqlite3_step(stmt) == SQLITE_DONE;
  if (!ok)
    err = sqlite3_errmsg(db_.handle());
  sqlite3_finalize(stmt);
  return ok;
}

}  // namespace lm

