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

#include "abstractcontroller.h"

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

#include <QHttpServerRequest>
#include <QJsonObject>
#include <utils.h>

using namespace Qt::Literals::StringLiterals;

QHttpServerResponse AbstractController::badRequest(const QString &reason)
{
    if (reason.isEmpty()) {
        return QHttpServerResponse(QJsonObject{{"errorMessage"_L1, "Invalid request"_L1}}, QHttpServerResponse::StatusCode::BadRequest);
    } else {
        return QHttpServerResponse(QJsonObject{{"errorMessage"_L1, QJsonValue("Invalid request: "_L1 + reason)}}, QHttpServerResponse::StatusCode::BadRequest);
    }
}

QHttpServerResponse AbstractController::forbidden()
{
    return QHttpServerResponse(QJsonObject{{"errorMessage"_L1, "Unable to authentificate"_L1}}, QHttpServerResponse::StatusCode::Forbidden);
}

std::optional<Client> AbstractController::checkAuthentification(const QHttpServerRequest &request)
{
    const auto &state = ServerState::instance();
    const auto email = QString::fromUtf8(Utils::findHeader(request.headers(), "X-EMAIL"));

    if (email.isEmpty() || !state.clients.contains(email)) {
        qCWarning(HTTP_LOG) << "no email found" << email;
        return std::nullopt;
    }

    return state.clients[email];
}
