#include "shop.hpp"
#include "../log.hpp"
#include <stdexcept>

int g_active_shop_id = 0;
int g_active_shop_subshop_id = 0;

static int cell_to_int(const Cell& cell) {
    if (cell.type == CellType::Int64) return static_cast<int>(cell.i64);
    if (cell.type == CellType::String && !cell.str.empty()) return std::stoi(cell.str);
    return 0;
}

bool fetch_active_shop() {
    ResultSet rs;
    if (!get_pool().execute(
            "SELECT TOP 1 kShop, kShopSubshop FROM dbo.tShopSubshop "
            "WHERE nGesperrt = 0 ORDER BY kShop",
            rs) || rs.empty()) {
        logc::warn("failed to load active shop from dbo.tShopSubshop");
        return false;
    }

    g_active_shop_id = cell_to_int(rs[0][0]);
    g_active_shop_subshop_id = rs[0].size() > 1 ? cell_to_int(rs[0][1]) : 0;
    logc::info("Active shop: kShop=%d kShopSubshop=%d", g_active_shop_id, g_active_shop_subshop_id);
    return g_active_shop_id > 0;
}
