#pragma once
#include "xml.hpp"
#include "session.hpp"
#include "warehouse.hpp"
#include "reserve.hpp"
#include "commit.hpp"
#include "deliver.hpp"
#include "../db/pool.hpp"

namespace delivery {

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

    int kWarenLager = resolve_outgoing_warehouse(c);
    int kSessionId = open_session(c, kBenutzer);

    try {
        reserve_positions(c, kBenutzer, kSessionId, kWarenLager, items);
        commit_picklists(c, kBenutzer, kSessionId, kAuftrag);
        deliver_picklists(c, kBenutzer, kSessionId, kAuftrag, kVersandArt);
    } catch (...) {
        try { discard_session(c, kBenutzer, kSessionId); } catch (...) {}
        try { close_session(c, kSessionId); } catch (...) {}
        throw;
    }

    try { discard_session(c, kBenutzer, kSessionId); } catch (...) {}
    try { close_session(c, kSessionId); } catch (...) {}
}

} // namespace delivery
