#include "../http.hpp"
#include "../tls_server.hpp"
#include "../router.hpp"
#include "../log.hpp"
#include "../queries/counts.hpp"
#include "../queries/customer_groups.hpp"
#include "../queries/shop.hpp"
#include "../config.hpp"

void handle_init(HttpRequest& req, HttpResponse& resp, RouteContext& /*ctx*/) {
    int64_t product_cursor = std::stoll(req.get_query_param("lastChangedProduct", "0"));
    int64_t category_cursor = std::stoll(req.get_query_param("lastChangedCategory", "0"));
    int64_t cg_cursor = std::stoll(req.get_query_param("lastChangedCustomerGroup", "0"));
    int64_t composite_cursor = std::stoll(req.get_query_param("lastChangedCompositeProduct", "0"));
    int64_t deleted_cursor = std::stoll(req.get_query_param("lastChangedDeletedEntity", "0"));

    int root = config::get_int("ROOT_CATEGORY_ID", 1);
    int shop = get_active_shop_id();

    int64_t product_count = 0, category_count = 0, cg_count = 0, composite_count = 0, deleted_count = 0;
    int64_t max_order_id_count = 0;

    if (get_pool().execute_scalar("SELECT 1") != 0) {
        product_count = get_product_count(root, shop, product_cursor);
        category_count = get_category_count(root, shop, category_cursor);
        cg_count = get_customer_group_count(cg_cursor);
        composite_count = get_composite_count(shop, composite_cursor);
        deleted_count = get_deleted_count(deleted_cursor);
        max_order_id_count = get_max_order_id_count(get_active_shop_subshop_id());
        logc::info("init counts: products=%lld categories=%lld cg=%lld composite=%lld deleted=%lld max_order=%lld root=%d shop=%d subshop=%d",
                   product_count, category_count, cg_count, composite_count, deleted_count, max_order_id_count,
                   root, shop, get_active_shop_subshop_id());
        if (product_cursor == 0 && category_cursor == 0 &&
            product_count == 0 && category_count == 0 && deleted_count == 0) {
            logc::warn("init: all counts zero with cursors at 0 — check DB connectivity and shop/category config");
        }
    } else {
        logc::warn("init: DB connection check failed, returning zero counts");
    }

    resp.send_json(200, {
        {"version", "1.10.12.0"},
        {"product_count", std::to_string(product_count)},
        {"category_count", std::to_string(category_count)},
        {"customer_count", "0"},
        {"customerGroup_count", std::to_string(cg_count)},
        {"compositeProduct_count", std::to_string(composite_count)},
        {"configurationGroup_count", "0"},
        {"configurationItem_count", "0"},
        {"deletedEntity_count", std::to_string(deleted_count)},
        {"max_orderId_count", std::to_string(max_order_id_count)}
    });
}
