#include <softbus_api/ExecuteCommand.h>

#include <softbus_core/models/ObjectModel.h>

namespace softbus::api {

ExecuteCommand ExecuteCommand::fromJson(const nlohmann::json& j)
{
    ExecuteCommand cmd;
    cmd.requestId = j.value("requestId", "");
    cmd.traceId = j.value("traceId", "");
    cmd.objectRef = j.value("objectRef", "");
    cmd.command = j.value("command", "");
    if (j.contains("params")) {
        cmd.params = j["params"];
    }
    return cmd;
}

nlohmann::json ExecuteCommand::toJson() const
{
    return nlohmann::json{
        {"type", "executeCommand"},
        {"requestId", requestId},
        {"traceId", traceId},
        {"objectRef", objectRef},
        {"command", command},
        {"params", params}
    };
}

bool ExecuteCommand::validate(std::string* error) const
{
    if (traceId.empty()) {
        if (error) {
            *error = "traceId is required";
        }
        return false;
    }
    if (objectRef.empty()) {
        if (error) {
            *error = "objectRef is required";
        }
        return false;
    }
    if (command.empty()) {
        if (error) {
            *error = "command is required";
        }
        return false;
    }
    if (!params.is_object()) {
        if (error) {
            *error = "params must be a JSON object";
        }
        return false;
    }
    const auto ref = softbus::core::ObjectRef::fromPath(objectRef);
    if (!ref.hasPoint()) {
        if (error) {
            *error = "objectRef must be a five-layer path (Site/System/Asset/Device/Point)";
        }
        return false;
    }
    return true;
}

} // namespace softbus::api
