#pragma once
#include "../db/pool.hpp"
#include "nlohmann/json.hpp"
#include "shop.hpp"
#include "../http.hpp"
#include "../config.hpp"

inline nlohmann::json get_category_list(int64_t cursor, int limit) {
    int root = config::get_int("ROOT_CATEGORY_ID", 1);
    int lang = config::get_int("LANGUAGE_ID", 1);
    int shop = get_active_shop_id();

    std::string sql =
        "WITH CategoryTree AS ("
        "  SELECT kKategorie FROM dbo.tKategorie WHERE kKategorie = ?"
        "  UNION ALL"
        "  SELECT t.kKategorie FROM dbo.tKategorie t"
        "  INNER JOIN CategoryTree ct ON t.kOberKategorie = ct.kKategorie"
        ") SELECT TOP (?) k.kKategorie AS id, k.kOberKategorie AS pid, "
        "k.nSort AS sort, ks.cName AS name, b.cHash AS imgHash, "
        "CONVERT(BIGINT, k.bRowversion) AS lastChanged "
        "FROM dbo.tKategorie k "
        "INNER JOIN dbo.tKategorieSprache ks ON ks.kKategorie = k.kKategorie AND ks.kSprache = ? "
        "LEFT JOIN dbo.tKategoriebildPlattform kbp ON kbp.kKategorie = k.kKategorie "
        "LEFT JOIN dbo.tBild b ON b.kBild = kbp.kBild "
        "WHERE k.kKategorie IN (SELECT kKategorie FROM CategoryTree WHERE kKategorie <> ?) "
        "AND k.cAktiv = 'Y' "
        "AND (? = 0 OR EXISTS (SELECT 1 FROM dbo.tKategorieShop ks2 "
        "WHERE ks2.kKategorie = k.kKategorie AND ks2.kShop = ?)) "
        "AND CONVERT(BIGINT, k.bRowversion) > ? "
        "ORDER BY lastChanged ASC";

    std::vector<Param> ps = {
        {ParamType::BigInt,"",root},{ParamType::Int,"",limit},
        {ParamType::Int,"",lang},{ParamType::BigInt,"",root},
        {ParamType::Int,"",shop},{ParamType::Int,"",shop},
        {ParamType::BigInt,"",cursor}
    };
    ResultSet rs;
    get_pool().execute(sql, ps, rs);
    auto ts = server_timestamp();
    nlohmann::json result = nlohmann::json::array();
    for (auto& row : rs) {
        std::string pid = (std::stoll(row[1].str) == root) ? "0" : row[1].str;
        result.push_back({
            {"_id", row[0].str},
            {"imghash", row[4].str.empty() ? nullptr : nlohmann::json(row[4].str)},
            {"imgsrc", row[4].str.empty() ? nullptr : nlohmann::json(row[4].str)},
            {"name", row[3].str},
            {"pid", pid},
            {"discounts", nlohmann::json::array()},
            {"sort", row[2].str},
            {"lastChanged", row[5].str},
            {"updated_at", ts},
            {"created_at", ts}
        });
    }
    return result;
}
