#include "api/http/RestApiRoutes.h"

#include <QHttpServer>
#include <QHttpServerRequest>
#include <QHttpServerResponse>
#include <QHttpServerResponder>
#include <QJsonObject>
#include <utility>

#include "api/http/RestApiCommandHttp.h"
#include "api/ipc_dbus/CommandDispatcher.h"

namespace softbus::api::http
{

void registerSoftbusRestApiRoutes(QHttpServer* server,
                                  QObject* routeContext,
                                  softbus::api::ipc::CommandDispatcher* dispatcher)
{
    if (!server || !routeContext || !dispatcher) {
        return;
    }

    server->route(QStringLiteral("/health"), QHttpServerRequest::Method::Get, routeContext, []() {
        return QHttpServerResponse(QJsonObject{{QStringLiteral("ok"), true}}, QHttpServerResponse::StatusCode::Ok);
    });

    server->route(QStringLiteral("/v1/status"), QHttpServerRequest::Method::Get, routeContext, [dispatcher]() {
        return makeCommandHttpResponse(QString(), dispatcher->dispatch(QStringLiteral("get_status"), {}));
    });

    server->route(QStringLiteral("/v1/command"), QHttpServerRequest::Method::Post, routeContext,
                  [dispatcher](const QHttpServerRequest& request) {
                      return handleExecuteCommandHttpBody(request.body(), *dispatcher);
                  });

    server->setMissingHandler(routeContext, [](const QHttpServerRequest&, QHttpServerResponder& responder) {
        QHttpServerResponse resp(QJsonObject{{QStringLiteral("error"), QStringLiteral("not_found")}},
                                 QHttpServerResponse::StatusCode::NotFound);
        responder.sendResponse(std::move(resp));
    });
}

} // namespace softbus::api::http
