#pragma once
#include "../db/pool.hpp"
#include "../log.hpp"
#include "nlohmann/json.hpp"

static const char* CUSTOMER_GROUP_IDS_SQL =
    "SELECT kKundenGruppe FROM dbo.tKundenGruppe ORDER BY kKundenGruppe";

static const char* CUSTOMER_GROUP_LIST_SQL =
    "SELECT kKundenGruppe AS id, cName AS name, nStandard AS standard, "
    "fRabatt AS discountPercent, CONVERT(BIGINT, bRowversion) AS lastChanged "
    "FROM dbo.tKundenGruppe WHERE CONVERT(BIGINT, bRowversion) > ? "
    "ORDER BY lastChanged ASC";

static const char* CUSTOMER_GROUP_COUNT_SQL =
    "SELECT COUNT(*) AS cnt FROM dbo.tKundenGruppe "
    "WHERE CONVERT(BIGINT, bRowversion) > ?";

inline std::vector<int64_t> get_customer_group_ids() {
    static std::vector<int64_t> cached;
    static bool loaded = false;
    if (loaded) return cached;

    ResultSet rs;
    if (!get_pool().execute(CUSTOMER_GROUP_IDS_SQL, rs)) {
        logc::warn("failed to load customer group ids");
        return {};
    }
    for (auto& row : rs) {
        cached.push_back(std::stoll(row[0].str));
    }
    loaded = true;
    return cached;
}

inline nlohmann::json get_customer_group_list(int64_t cursor = 0) {
    Param p; p.type = ParamType::BigInt; p.int_val = cursor;
    ResultSet rs;
    get_pool().execute(CUSTOMER_GROUP_LIST_SQL, {p}, rs);
    nlohmann::json result = nlohmann::json::array();
    for (auto& row : rs) {
        result.push_back({
            {"customerGroupId", row[0].str},
            {"name", row[1].str},
            {"standard", row[2].str},
            {"discountPercent", std::to_string(std::stod(row[3].str))},
            {"lastChanged", row[4].str}
        });
    }
    return result;
}

inline int64_t get_customer_group_count(int64_t cursor = 0) {
    Param p; p.type = ParamType::BigInt; p.int_val = cursor;
    return get_pool().execute_scalar(CUSTOMER_GROUP_COUNT_SQL, {p});
}
