#include "api/http/RestApiCommandHttp.h"

#include <QHttpServerResponse>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

#include "api/ipc_dbus/CommandDispatcher.h"

namespace softbus::api::http
{

QHttpServerResponse makeCommandHttpResponse(const QString& id, const softbus::api::ipc::DispatchResult& r)
{
    QJsonObject o;
    o.insert(QStringLiteral("id"), id);
    o.insert(QStringLiteral("code"), r.code);
    o.insert(QStringLiteral("message"), r.message);
    o.insert(QStringLiteral("data"), r.data);
    const auto httpStatus =
        r.code == 0 ? QHttpServerResponse::StatusCode::Ok : QHttpServerResponse::StatusCode::BadRequest;
    return QHttpServerResponse(o, httpStatus);
}

QHttpServerResponse handleExecuteCommandHttpBody(const QByteArray& body, softbus::api::ipc::CommandDispatcher& dispatcher)
{
    QJsonParseError err;
    const QJsonDocument doc = QJsonDocument::fromJson(body, &err);
    if (err.error != QJsonParseError::NoError || !doc.isObject()) {
        return makeCommandHttpResponse(QString(), {4000, QStringLiteral("invalid_json"), {}});
    }
    const QJsonObject req = doc.object();
    const QString id = req.value(QStringLiteral("id")).toString();
    const QString action = req.value(QStringLiteral("action")).toString();
    const QJsonObject params = req.value(QStringLiteral("params")).toObject();
    if (action.isEmpty()) {
        return makeCommandHttpResponse(id, {4003, QStringLiteral("invalid_action"), {}});
    }
    const auto result = dispatcher.dispatch(action, params);
    return makeCommandHttpResponse(id, result);
}

} // namespace softbus::api::http
