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

namespace delivery {

inline int open_session(OdbcPool::Connection* c, int kBenutzer,
                        const std::string& hostname = "jtlsrv") {
    const char* sql =
        "DECLARE @t TABLE ([kSessionId] INT);"
        "INSERT INTO dbo.tSessionId (cRechnername, kBenutzer, dLastAction)"
        " OUTPUT inserted.kSessionId INTO @t"
        " VALUES (?, ?, DATEADD(day, 10, GETDATE()));"
        "SELECT kSessionId FROM @t;";

    std::vector<Param> ps = {
        {ParamType::NVarChar, hostname, 0},
        {ParamType::Int, "", kBenutzer}
    };
    ResultSet rs;
    if (!get_pool().execute(c, sql, ps, rs) || rs.empty() || rs[0].empty()) {
        throw std::runtime_error("failed to open delivery session");
    }
    return std::stoi(rs[0][0].str);
}

inline void discard_session(OdbcPool::Connection* c, int kBenutzer, int kSessionId) {
    std::vector<Param> ps = {
        {ParamType::Int, "", kBenutzer},
        {ParamType::Int, "", kSessionId}
    };
    ResultSet rs;
    get_pool().execute(c, "{CALL Auslieferung.spPicklistenVerwerfen(?, ?)}", ps, rs);
}

inline void close_session(OdbcPool::Connection* c, int kSessionId) {
    std::vector<Param> ps = {{ParamType::Int, "", kSessionId}};
    ResultSet rs;
    get_pool().execute(c, "DELETE FROM dbo.tSessionId WHERE kSessionId = ?", ps, rs);
}

} // namespace delivery
