#pragma once
#include "result.hpp"
#include <algorithm>
#include <ranges>
#include <set>
#include <span>
#include <string_view>
#include <vector>

namespace orders {
enum class Status { open, done };
struct Order {
  int id;
  std::string title;
  int priority{0};
  Status status{Status::open};
  bool operator==(const Order &) const = default;
};
inline Result<Done> validate(const Order &order) {
  const bool blank = std::ranges::all_of(order.title, [](char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  });
  if (order.id < 1 || order.id > 1000000 || order.title.empty() ||
      order.title.size() > 80 || blank || order.priority < 0 ||
      order.priority > 2 ||
      (order.status != Status::open && order.status != Status::done))
    return Error{ErrorCode::invalid, "ID 1..1000000, title 1..80 UTF-8 bytes, "
                                     "priority 0..2 and valid status required"};
  return Done{};
}
inline Result<Done> validateBatch(std::span<const Order> batch) {
  if (batch.size() > 1000)
    return Error{ErrorCode::invalid, "At most 1000 orders are allowed"};
  std::set<int> ids;
  for (const auto &order : batch) {
    auto result = validate(order);
    if (!succeeded(result))
      return std::get<Error>(result);
    if (!ids.insert(order.id).second)
      return Error{ErrorCode::duplicate, "Duplicate order ID"};
  }
  return Done{};
}
inline std::vector<int> matchingIds(std::span<const Order> values,
                                    std::string_view needle) {
  // Both views borrow their input. Consume them before the owner changes.
  auto matching =
      values | std::views::filter([needle](const Order &order) {
        return order.status == Status::open &&
               order.title.find(needle) != std::string::npos;
      }) |
      std::views::transform([](const Order &order) { return order.id; });
  return {matching.begin(), matching.end()};
}
inline Result<Done> replaceValidated(std::vector<Order> &current,
                                     std::span<const Order> incoming) {
  auto result = validateBatch(incoming);
  if (!succeeded(result))
    return std::get<Error>(result);
  std::vector<Order> candidate(incoming.begin(), incoming.end());
  // Validation and allocations precede this non-throwing commit point.
  current.swap(candidate);
  return Done{};
}
} // namespace orders
