#include <fastly/sdk.h>
#include <nlohmann/json.hpp> // Available in Fastly Fiddle
#include <string>

using json = nlohmann::json;

int main(int argc, char* argv[]) {
    auto req = fastly::Request::from_client();

    auto beresp_res = req.send("http_me");
    if (!beresp_res.has_value()) {
        auto error_res = fastly::Response::from_status(502).with_body("Bad Gateway: Backend fetch failed.");
        error_res.send_to_client();
        return 0;
    }

    // Read the backend response body into a standard string.
    std::string body_str = beresp_res->take_body().take_body_string();

    // Parse the string into a JSON object using nlohmann/json.
    auto new_json = json::parse(body_str);

    // Mutate the JSON payload (adds a new field).
    new_json["new_field"] = "content";

    // Serialize the modified JSON back into a string representation.
    std::string modified_body = new_json.dump();

    beresp_res->set_body(modified_body);

    beresp_res->send_to_client();

    return 0;
}