// SPDX-FileCopyrightText: 2024 g10 code GmbH
// SPDX-FileContributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: LGPL-2.0-or-later

#include "ewsmessagedispatcher.h"
#include "editor_debug.h"
#include "ewsmailfactory.h"
#include "qnam.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>

#include <KLocalizedString>

using namespace Qt::StringLiterals;

EWSMessageDispatcher::EWSMessageDispatcher(QObject *parent)
    : MessageDispatcher(parent)
{
}

void EWSMessageDispatcher::dispatch(const KMime::Message::Ptr &message, const QString &from, const QString &mailId)
{
    qWarning().noquote() << message->encodedContent();

    auto soapRequestBody = EwsMailFactory::create(message);

    QNetworkRequest sendMailRequest(QUrl(u"https://127.0.0.1:5656/socket-web"_s));
    sendMailRequest.setHeader(QNetworkRequest::ContentTypeHeader, u"application/xml"_s);
    sendMailRequest.setRawHeader("X-TOKEN", m_bearerToken);
    sendMailRequest.setRawHeader("X-EMAIL", from.toUtf8());

    const QJsonDocument payload(QJsonObject{
        {"type"_L1, "ews"_L1},
        {"payload"_L1, soapRequestBody},
        {"id"_L1, mailId},
    });

    auto sendMailResponse = qnam->post(sendMailRequest, payload.toJson());

    // TODO remove me
    QObject::connect(qnam, &QNetworkAccessManager::sslErrors, qnam, [](QNetworkReply *reply, const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        reply->ignoreSslErrors();
    });

    connect(sendMailResponse, &QNetworkReply::finished, this, [this, sendMailResponse]() {
        if (sendMailResponse->error() != QNetworkReply::NoError) {
            Q_EMIT errorOccurred(i18nc("Error message", "There were a problem sending the message: %1", sendMailResponse->errorString()));
            return;
        }

        Q_EMIT sentSuccessfully();
    });

    qCDebug(EDITOR_LOG) << "Request body" << soapRequestBody;
}

QByteArray EWSMessageDispatcher::bearerToken() const
{
    return m_bearerToken;
}

void EWSMessageDispatcher::setBearerToken(const QByteArray &bearerToken)
{
    m_bearerToken = bearerToken;
}
