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

inline nlohmann::json get_composite_product_list(int64_t cursor, int limit) {
    int shop = get_active_shop_id();
    std::string sql =
        "SELECT TOP (?) s.kVaterArtikel AS productId, "
        "s.kArtikel AS productIdComponent, "
        "CONVERT(VARCHAR(20), s.fAnzahl, 2) AS quantity, "
        "CONVERT(BIGINT, a.bRowversion) AS lastChanged "
        "FROM dbo.tStueckliste s "
        "INNER JOIN dbo.tArtikel a ON a.kArtikel = s.kVaterArtikel "
        "WHERE a.kStueckliste <> 0 "
        "AND (? = 0 OR EXISTS (SELECT 1 FROM dbo.tKategorieArtikel ka "
        "INNER JOIN dbo.tKategorieShop ks ON ks.kKategorie = ka.kKategorie "
        "AND ks.kShop = ? WHERE ka.kArtikel = a.kArtikel)) "
        "AND CONVERT(BIGINT, a.bRowversion) > ? "
        "ORDER BY lastChanged ASC";

    std::vector<Param> ps = {
        {ParamType::Int,"",limit},
        {ParamType::Int,"",shop},
        {ParamType::Int,"",shop},
        {ParamType::BigInt,"",cursor}
    };
    ResultSet rs;
    get_pool().execute(sql, ps, rs);
    nlohmann::json result = nlohmann::json::array();
    for (auto& row : rs) {
        result.push_back({
            {"productId", row[0].str},
            {"productIdComponent", row[1].str},
            {"quantity", row[2].str},
            {"lastChanged", row[3].str}
        });
    }
    return result;
}
