// http_get_json.cpp — wrapper over fn_http::request that returns parsed JSON.
// Issue 0110.
#include "core/http_get_json.h"
#include "core/http_request.h"

#include <stdexcept>
#include <string>

namespace fn_http {

nlohmann::json get_json(const std::string& url,
                        const std::string& bearer_token,
                        int                timeout_ms) {
    Request req;
    req.method       = "GET";
    req.url          = url;
    req.timeout_ms   = timeout_ms;
    req.bearer_token = bearer_token;
    req.headers      = {{"Accept", "application/json"}};

    Response res = request(req);

    if (!res.error.empty()) {
        throw std::runtime_error("http_get_json: transport error: " + res.error);
    }
    if (res.status / 100 != 2) {
        throw std::runtime_error(
            "http_get_json: HTTP " + std::to_string(res.status) +
            " from " + url +
            (res.body.empty() ? std::string() : ": " + res.body.substr(0, 200)));
    }

    try {
        return nlohmann::json::parse(res.body);
    } catch (const nlohmann::json::parse_error& e) {
        throw std::runtime_error(
            "http_get_json: invalid JSON from " + url + ": " + e.what());
    }
}

} // namespace fn_http
