#include "factory/application/document.h"
#include "factory/core/pathfinder.h"
#include <algorithm>
#include <stdexcept>

namespace factory {
Document::Document(std::shared_ptr<ProjectRepository> repository)
    : repository_(std::move(repository)) {
  if (!repository_)
    throw std::invalid_argument("Repository is required");
  replace(Project{});
}
bool Document::edit(const std::function<void(Project&)>& change) {
  auto next = project();
  change(next);
  if (next == project())
    return false;
  history_.erase(history_.begin() + static_cast<std::ptrdiff_t>(cursor_ + 1), history_.end());
  history_.push_back(std::move(next));
  if (history_.size() > 101)
    history_.erase(history_.begin());
  cursor_ = history_.size() - 1;
  return true;
}
void Document::undo() {
  if (canUndo())
    --cursor_;
}
void Document::redo() {
  if (canRedo())
    ++cursor_;
}
void Document::replace(Project project) {
  saved_ = project;
  history_ = {std::move(project)};
  cursor_ = 0;
  path_.clear();
}
void Document::load(const std::string& path) {
  auto loaded = repository_->load(path);
  replace(std::move(loaded));
  path_ = path;
}
void Document::save(const std::string& path) {
  repository_->save(project(), path);
  saved_ = project();
  path_ = path;
}
std::vector<std::string> preflight(const Project& p) {
  auto issues = p.validate();
  if (!issues.empty())
    return issues;
  for (const auto& order : p.orders) {
    if (findPath(p, order.pickup, order.delivery).empty())
      issues.push_back("Order " + std::to_string(order.id) +
                       ": connect pickup and delivery with roads");
    const bool reachable = std::ranges::any_of(
        p.vehicles, [&](const auto& v) { return !findPath(p, v.home, order.pickup).empty(); });
    if (!reachable)
      issues.push_back("Order " + std::to_string(order.id) + ": no vehicle can reach the pickup");
  }
  return issues;
}
} // namespace factory
