// GET /v1/client — pairing handshake (no DB)
// Port of src/endpoints/client.js

#include "../http.hpp"
#include "../pairing.hpp"
#include "../tls_server.hpp"
#include "../router.hpp"

static json build_client_step1(const json& config) {
    return {
        {"authCode", nullptr},
        {"authToken", config["authToken"]},
        {"certificateFingerprint", config["certificateFingerprint"]},
        {"certificateSerialNumber", config["certificateSerialNumber"]},
        {"mandantId", config["mandantId"]},
        {"mandantName", nullptr},
        {"mandantDatabase", nullptr},
        {"serverFingerprint", config["serverFingerprint"]},
        {"name", nullptr},
        {"serverTimestamp", server_timestamp()},
    };
}

static json build_client_step2(const std::string& auth_code, const json& config) {
    return {
        {"authCode", auth_code},
        {"authToken", config["authToken"]},
        {"certificateFingerprint", config["certificateFingerprint"]},
        {"certificateSerialNumber", config["certificateSerialNumber"]},
        {"mandantId", config["mandantId"]},
        {"mandantName", config["mandantName"]},
        {"mandantDatabase", config["mandantDatabase"]},
        {"serverFingerprint", nullptr},
        {"name", nullptr},
        {"serverTimestamp", server_timestamp()},
    };
}

void handle_client(HttpRequest& req, HttpResponse& resp, RouteContext& ctx) {
    std::string auth_code = req.get_query_param("authCode");
    std::string name = req.get_query_param("name", "JTL-POS");

    if (auth_code.size() <= 4 && !auth_code.empty()) {
        return resp.send_json(200, build_client_step1(ctx.config));
    }

    if (auth_code.size() == 6) {
        if (ctx.pairing_store->has_pairing_code(auth_code)) {
            ctx.pairing_store->revoke_pairing_code(auth_code);
            ctx.pairing_store->register_device(ctx.config["authToken"].get<std::string>(), name);
            return resp.send_json(200, build_client_step2(auth_code, ctx.config));
        }
        return resp.send_json(400, {
            {"Message", "Der Authentifizierungscode ist falsch."}
        });
    }

    return resp.send_json(400, {
        {"Message", "Keinen passenden Authentifizierungscode gefunden."}
    });
}
