// SPDX-FileCopyrightText: 2023 g10 code GmbH
// SPDX-Contributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "registrationcontroller.h"

#include <QCryptographicHash>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QString>

#include "../model/serverstate.h"
#include "http_debug.h"

using namespace Qt::Literals::StringLiterals;

QHttpServerResponse RegistrationController::registerAction(const QHttpServerRequest &request)
{
    const auto json = QJsonDocument::fromJson(request.body());
    if (json.isEmpty() || !json.isObject()) {
        return badRequest();
    }

    const auto object = json.object();

    if (object.isEmpty() || !object.contains("port"_L1) || !object.contains("emails"_L1)) {
        return badRequest();
    }

    const auto emails = object["emails"_L1].toArray();
    const Client::Id clientId = object["clientId"_L1].toString();
    const auto port = object["port"_L1].toInt();
    for (const auto email : emails) {
        ServerState::instance().clients[email.toString().toLower()] = Client{
            clientId,
            port,
        };

        qCInfo(HTTP_LOG) << "Registration of email" << email.toString() << "on port" << object["port"_L1].toInt() << "with clientId" << clientId;
    }

    return QHttpServerResponse("text/plain", "Server added\n");
}
