#pragma once
#include <string>
#include <vector>
#include "xml.hpp"
#include "../db/pool.hpp"

namespace delivery {

struct DeliveredItem {
    int kAuftragPosition;
    double quantity;
};

inline void reserve_positions(OdbcPool::Connection* c, int kBenutzer, int kSessionId,
                              int kWarenLager, const std::vector<DeliveredItem>& items) {
    if (items.empty()) return;

    std::string bestellpositionen;
    for (const auto& it : items) {
        bestellpositionen += xml::element("Bestellposition",
            xml::tag("kBestellPos", int64_t(it.kAuftragPosition)) +
            xml::tag("fAnzahl", it.quantity));
    }

    std::string laeger = xml::element("Lager",
        xml::tag("kWarenlager", int64_t(kWarenLager)) +
        xml::tag("nPrio", int64_t(0)) +
        xml::tag("kLieferant", int64_t(0)) +
        xml::tag("kAnsprechpartner", int64_t(0)));

    const int RESERVIERE_OPTIONS = 0x102;

    const char* sql =
        "DECLARE @xBestellpositionen XML = CONVERT(XML, ?);"
        "DECLARE @xLaeger XML = CONVERT(XML, ?);"
        "EXEC Auslieferung.spReserviereBestellpositionen"
        " @Bestellpositionen = @xBestellpositionen,"
        " @Laeger = @xLaeger,"
        " @Warenlagereingaenge = NULL,"
        " @nOptions = ?,"
        " @kBenutzer = ?,"
        " @kSessionId = ?";

    std::vector<Param> ps = {
        {ParamType::NVarChar, bestellpositionen, 0},
        {ParamType::NVarChar, laeger, 0},
        {ParamType::Int, "", RESERVIERE_OPTIONS},
        {ParamType::Int, "", kBenutzer},
        {ParamType::Int, "", kSessionId}
    };
    ResultSet rs;
    if (!get_pool().execute(c, sql, ps, rs)) {
        throw std::runtime_error("reserve_positions failed");
    }
}

} // namespace delivery
