// POST /v1/order — creates one or more POS orders.
// Port of src/endpoints/order.js and src/queries/create-order.js.

#include "../http.hpp"
#include "../router.hpp"
#include "../log.hpp"
#include "../order_log.hpp"
#include "../queries/create_order.hpp"

#include <string>

static nlohmann::json get_orders(const nlohmann::json& body) {
    if (!body.is_object()) return nlohmann::json::array();
    auto it = body.find("orders");
    if (it == body.end() || !it->is_array()) return nlohmann::json::array();
    return *it;
}

void handle_order(HttpRequest& req, HttpResponse& resp, RouteContext& /*ctx*/) {
    nlohmann::json body;
    try {
        body = nlohmann::json::parse(req.body);
    } catch (...) {
        return resp.send_json(500, nlohmann::json::array());
    }

    nlohmann::json results = nlohmann::json::array();
    nlohmann::json orders = get_orders(body);

    int successful = 0;
    int failed = 0;

    for (const auto& order : orders) {
        std::string externalOrderId = order.value("externalId", "");
        g_order_log.log_order(order.dump(), externalOrderId);

        try {
            nlohmann::json created = order::create_order(order);
            logc::success("order %s (kAuftrag=%s) created for externalId=%s",
                          created.value("orderNumber", "").c_str(),
                          created.value("orderId", "").c_str(),
                          externalOrderId.c_str());
            results.push_back({
                {"status", "OK"},
                {"externalOrderId", externalOrderId},
                {"message", ""}
            });
            ++successful;
        } catch (const std::exception& ex) {
            logc::error("order externalId=%s failed: %s", externalOrderId.c_str(), ex.what());
            results.push_back({
                {"status", "ERROR"},
                {"externalOrderId", externalOrderId},
                {"message", ex.what()}
            });
            ++failed;
        }
    }

    resp.send_json(200, results);

    if (orders.empty()) {
        logc::info("POST /v1/order: no orders in body");
    } else {
        logc::info("POST /v1/order: %d order(s), %d OK, %d ERROR",
                   static_cast<int>(orders.size()), successful, failed);
    }
}
