#include "outlooksynchronizer.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QUrlQuery>
#include <QDateTime>
#include <QTimer>
#include <QEventLoop>
#include "../../core/events.h"
#include "../../core/eventbus.h"
#include "db/dao/folderdao.h"
#include "services/mimestorage.h"

OutlookSynchronizer::OutlookSynchronizer(QObject* parent)
    : Synchronizer(parent),
      m_networkManager(new QNetworkAccessManager(this)),
      m_deltaTimer(new QTimer(this))
{
    // Conectar señales
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &OutlookSynchronizer::onGraphReplyFinished);
    connect(m_deltaTimer, &QTimer::timeout,
            this, &OutlookSynchronizer::onDeltaLinkTimer);
    
    // Configurar timer para delta sync cada 5 minutos
    m_deltaTimer->setInterval(5 * 60 * 1000); // 5 minutos
}

bool OutlookSynchronizer::initialize(const Account& account)
{
    // Guardar información de la cuenta
    m_account = account;
    
    // Para Outlook, usamos tokens de acceso
    m_accessToken = account.accessToken();
    m_refreshToken = account.refreshToken();
    m_tokenExpires = account.tokenExpires();
    
    if (m_accessToken.isEmpty()) {
        qWarning() << "Outlook account has no access token";
        return false;
    }
    
    // Publish AccountConnectedEvent
    WinoMail::Events::AccountConnectedEvent event;
    event.eventId = QString::number(QDateTime::currentMSecsSinceEpoch()) + "_" + QString::number(rand());
    event.timestamp = QDateTime::currentDateTimeUtc();
    event.accountId = account.id();
    event.provider = "outlook";
    PUBLISH(event);
    
    qDebug() << "Outlook Synchronizer initialized for account:" << account.email();
    return true;
}

bool OutlookSynchronizer::syncFolder(const Folder& folder)
{
    if (!m_account.isTokenValid()) {
        if (!refreshAccessToken()) {
            qWarning() << "Failed to refresh token for Outlook sync";
            emit errorOccurred("Failed to refresh authentication token");
            return false;
        }
    }
    
    qDebug() << "Starting Outlook sync for folder:" << folder.name();
    
    // Publish SyncStartedEvent
    WinoMail::Events::SyncStartedEvent syncStartEvent;
    syncStartEvent.eventId = QString::number(QDateTime::currentMSecsSinceEpoch()) + "_" + QString::number(rand());
    syncStartEvent.timestamp = QDateTime::currentDateTimeUtc();
    syncStartEvent.accountId = m_account.id();
    syncStartEvent.folderId = QString::number(folder.id());
    PUBLISH(syncStartEvent);
    
    emit folderSyncStarted(QString::number(folder.id()));
    
    // Obtener elementos de correo desde Microsoft Graph
    QVector<MailItem> items = fetchMailItems(QString::number(folder.id()));
    
    // En una implementación real, aquí compararíamos con la base de datos local
    // y emitiríamos las señales apropiadas para elementos nuevos/actualizados/eliminados
    
    if (!items.isEmpty()) {
        for (const MailItem& item : items) {
            emit mailItemAdded(item);
            // Publish MailItemAddedEvent
            WinoMail::Events::MailItemAddedEvent mailEvent;
            mailEvent.eventId = QString::number(QDateTime::currentMSecsSinceEpoch()) + "_" + QString::number(rand());
            mailEvent.timestamp = QDateTime::currentDateTimeUtc();
            mailEvent.item = item;
            PUBLISH(mailEvent);
        }
    }
    
    emit folderSyncFinished(QString::number(folder.id()), true);
    
    // Publish SyncFinishedEvent
    WinoMail::Events::SyncFinishedEvent syncFinishEvent;
    syncFinishEvent.eventId = QString::number(QDateTime::currentMSecsSinceEpoch()) + "_" + QString::number(rand());
    syncFinishEvent.timestamp = QDateTime::currentDateTimeUtc();
    syncFinishEvent.accountId = m_account.id();
    syncFinishEvent.folderId = QString::number(folder.id());
    syncFinishEvent.success = true;
    syncFinishEvent.errorMessage = "";
    PUBLISH(syncFinishEvent);
    
    return true;
}

QVector<Folder> OutlookSynchronizer::getFolders() const
{
    // En una implementación real, llamaríamos a Microsoft Graph API
    // para obtener las carpetas del buzón
    // Por ahora, devolvemos algunas carpetas básicas
    
    QVector<Folder> folders;
    folders.append(Folder(1, m_account.id(), "Inbox", "Inbox", true, false, false, false, 0, QDateTime::currentDateTime()));
    folders.append(Folder(2, m_account.id(), "Drafts", "Drafts", false, true, false, false, 0, QDateTime::currentDateTime()));
    folders.append(Folder(3, m_account.id(), "Sent Items", "SentMail", false, false, true, false, 0, QDateTime::currentDateTime()));
    folders.append(Folder(4, m_account.id(), "Trash", "DeletedItems", false, false, false, true, 0, QDateTime::currentDateTime()));
    
    return folders;
}

QVector<MailItem> OutlookSynchronizer::fetchMailItems(const QString& folderId, 
                                                     qint64 sinceUid)
{
    Q_UNUSED(sinceUid); // En Outlook usamos delta links en lugar de UIDs
    
    if (!m_account.isTokenValid()) {
        if (!refreshAccessToken()) {
            qWarning() << "Failed to refresh token for fetching mail items";
            return QVector<MailItem>();
        }
    }
    
    qDebug() << "Fetching complete Outlook messages for folder:" << folderId;

    QString remoteFolderId = folderId;
    bool localFolderId = false;
    folderId.toInt(&localFolderId);
    if (localFolderId) {
        const auto folder = FolderDao::findById(folderId.toInt());
        if (folder) {
            remoteFolderId = folder->parentFolderId();
            if (remoteFolderId.isEmpty()) {
                const QString name = folder->name().toLower();
                if (name == QStringLiteral("inbox")) remoteFolderId = QStringLiteral("inbox");
                else if (name == QStringLiteral("sent") || name == QStringLiteral("sent items")) remoteFolderId = QStringLiteral("sentitems");
                else if (name == QStringLiteral("drafts")) remoteFolderId = QStringLiteral("drafts");
                else if (name == QStringLiteral("trash") || name == QStringLiteral("deleted items")) remoteFolderId = QStringLiteral("deleteditems");
                else remoteFolderId = folder->name();
            }
        }
    }

    QNetworkAccessManager network;
    auto get = [&](const QUrl &url, QByteArray &data) {
        QNetworkRequest request = createAuthRequest(url.toString());
        request.setRawHeader("Accept", "message/rfc822, application/json");
        QNetworkReply *reply = network.get(request);
        QEventLoop loop;
        QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();
        const bool ok = reply->error() == QNetworkReply::NoError;
        if (ok) data = reply->readAll();
        else qWarning() << "Outlook request failed:" << reply->errorString() << url;
        reply->deleteLater();
        return ok;
    };

    QVector<QJsonObject> messageRefs;
    QUrl nextUrl(buildGraphUrl(QStringLiteral("/me/mailFolders/%1/messages").arg(remoteFolderId)));
    QUrlQuery query;
    query.addQueryItem(QStringLiteral("$top"), QStringLiteral("100"));
    query.addQueryItem(QStringLiteral("$select"), QStringLiteral("id,isRead,importance"));
    query.addQueryItem(QStringLiteral("$orderby"), QStringLiteral("receivedDateTime DESC"));
    nextUrl.setQuery(query);
    while (nextUrl.isValid() && !nextUrl.toString().isEmpty()) {
        QByteArray response;
        if (!get(nextUrl, response)) return {};
        QJsonParseError parseError;
        const QJsonDocument document = QJsonDocument::fromJson(response, &parseError);
        if (parseError.error != QJsonParseError::NoError || !document.isObject()) return {};
        const QJsonObject object = document.object();
        for (const QJsonValue &value : object.value(QStringLiteral("value")).toArray())
            if (value.isObject()) messageRefs.append(value.toObject());
        const QString continuation = object.value(QStringLiteral("@odata.nextLink")).toString();
        nextUrl = continuation.isEmpty() ? QUrl() : QUrl(continuation);
    }

    QVector<MailItem> items;
    MimeStorageService mimeStorage;
    for (const QJsonObject &reference : messageRefs) {
        const QString messageId = reference.value(QStringLiteral("id")).toString();
        if (messageId.isEmpty()) continue;
        const QString encodedId = QString::fromUtf8(QUrl::toPercentEncoding(messageId));
        const QUrl rawUrl(buildGraphUrl(QStringLiteral("/me/messages/%1/$value").arg(encodedId)));
        QByteArray rawMime;
        if (!get(rawUrl, rawMime) || rawMime.isEmpty()) continue;
        ParsedMimeMessage parsed;
        if (!mimeStorage.parseMessage(rawMime, parsed)) continue;

        MailItem item;
        item.setFolderId(folderId.toInt());
        item.setMessageId(messageId);
        item.setRawMime(rawMime);
        item.setSubject(parsed.subject.isEmpty() ? QStringLiteral("(No Subject)") : parsed.subject);
        item.setSender(parsed.from);
        item.setRecipient(parsed.to);
        item.setTo(parsed.to);
        item.setCc(parsed.cc);
        item.setBcc(parsed.bcc);
        item.setDate(parsed.date);
        item.setBodyHtml(parsed.bodyHtml);
        item.setSize(rawMime.size());
        item.setRead(reference.value(QStringLiteral("isRead")).toBool(true));
        item.setFlagged(reference.value(QStringLiteral("importance")).toString() == QStringLiteral("high"));
        QVector<QString> attachmentNames;
        for (const ParsedMimeAttachment &attachment : parsed.attachments) attachmentNames.append(attachment.fileName);
        item.setAttachments(attachmentNames);
        items.append(item);
    }
    return items;
}

bool OutlookSynchronizer::appendMailItem(const QString& folderId, const MailItem& item)
{
    Q_UNUSED(folderId);
    Q_UNUSED(item);
    qWarning() << "Outlook appendMailItem is not used for sending; MailService sends via Graph API";
    return false;
}

bool OutlookSynchronizer::updateMailItemFlags(const QString& folderId, 
                                             const QString& itemUid,
                                             bool read, bool flagged)
{
    Q_UNUSED(folderId);
    Q_UNUSED(itemUid);
    Q_UNUSED(read);
    Q_UNUSED(flagged);
    qWarning() << "Outlook flag update is not available through this synchronizer";
    return false;
}

bool OutlookSynchronizer::deleteMailItem(const QString& folderId, 
                                        const QString& itemUid)
{
    Q_UNUSED(folderId);
    Q_UNUSED(itemUid);
    qWarning() << "Outlook delete is not available through this synchronizer";
    return false;
}

void OutlookSynchronizer::onGraphReplyFinished(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "Graph API error:" << reply->errorString();
        emit errorOccurred(reply->errorString());
        reply->deleteLater();
        return;
    }
    
    QByteArray responseData = reply->readAll();
    reply->deleteLater();
    
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "Failed to parse Graph API response:" << parseError.errorString();
        emit errorOccurred("Failed to parse server response");
        return;
    }
    
    if (!doc.isObject()) {
        qWarning() << "Graph API response is not an object";
        emit errorOccurred("Invalid server response");
        return;
    }
    
    QJsonObject obj = doc.object();
    
    // Procesar según el tipo de llamada
    // En una implementación completa, aquí manejaríamos las respuestas
    // para obtener carpetas, mensajes, etc.
    
    qDebug() << "Graph API response received successfully";
}

void OutlookSynchronizer::onDeltaLinkTimer()
{
    qDebug() << "Delta link timer fired - checking for changes";
    
    // En una implementación real, aquí usaríamos los delta links
    // obtenidos previamente para consultar solo los cambios
    // desde la última sincronización
    
    // Por ahora, simplemente iniciamos una sincronización completa
    // de todas las carpetas (esto sería ineficiente en producción)
    QVector<Folder> folders = getFolders();
    for (const Folder& folder : folders) {
        syncFolder(folder);
    }
}

QString OutlookSynchronizer::buildGraphUrl(const QString& endpoint) const
{
    return QStringLiteral("https://graph.microsoft.com/v1.0%1").arg(endpoint);
}

QNetworkRequest OutlookSynchronizer::createAuthRequest(const QString& url) const
{
    QNetworkRequest request{QUrl(url)};
    request.setRawHeader("Authorization", 
                        QString("Bearer %1").arg(m_accessToken).toUtf8());
    request.setHeader(QNetworkRequest::ContentTypeHeader, 
                     "application/json");
    return request;
}

bool OutlookSynchronizer::refreshAccessToken()
{
    // En una implementación real, aquí usaríamos el refresh token
    // para obtener un nuevo access token desde Azure AD
    
    if (m_refreshToken.isEmpty()) {
        qWarning() << "No refresh token available for Outlook";
        return false;
    }

    const QString clientId = qEnvironmentVariable("WINO_OUTLOOK_CLIENT_ID");
    const QString clientSecret = qEnvironmentVariable("WINO_OUTLOOK_CLIENT_SECRET");
    if (clientId.isEmpty() || clientSecret.isEmpty()) {
        qWarning() << "Outlook token expired and WINO_OUTLOOK_CLIENT_ID/SECRET are not configured";
        return false;
    }
    const QString tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";

    QNetworkRequest networkRequest{QUrl(tokenUrl)};
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QUrlQuery postData;
    postData.addQueryItem("client_id", clientId);
    postData.addQueryItem("scope", "Mail.Read Mail.ReadWrite Mail.Send offline_access");
    postData.addQueryItem("refresh_token", m_refreshToken);
    postData.addQueryItem("grant_type", "refresh_token");
    postData.addQueryItem("client_secret", clientSecret);

    QNetworkAccessManager network;
    QNetworkReply* reply = network.post(networkRequest, postData.toString(QUrl::FullyEncoded).toUtf8());

    // Wait for reply synchronously for simplicity in this context
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "Outlook token refresh failed:" << reply->errorString();
        reply->deleteLater();
        return false;
    }

    QByteArray responseData = reply->readAll();
    reply->deleteLater();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "Failed to parse Outlook token response:" << parseError.errorString();
        return false;
    }

    QJsonObject obj = doc.object();
    if (!obj.contains("access_token")) {
        qWarning() << "No access_token in Outlook token response";
        return false;
    }

    m_accessToken = obj["access_token"].toString();
    int expiresIn = obj["expires_in"].toInt(3600); // default 1 hour
    m_tokenExpires = QDateTime::currentDateTimeUtc().addSecs(expiresIn);

    // Update refresh token if provided (sometimes rotation is used)
    if (obj.contains("refresh_token")) {
        m_refreshToken = obj["refresh_token"].toString();
    }

    qDebug() << "Outlook access token refreshed successfully, expires in" << expiresIn << "seconds";
    return true;
}

QString OutlookSynchronizer::getDeltaLink(const QString& folderId) const
{
    return m_deltaLinks.value(folderId, QString());
}

void OutlookSynchronizer::setDeltaLink(const QString& folderId, const QString& deltaLink)
{
    m_deltaLinks.insert(folderId, deltaLink);
}

MailItem OutlookSynchronizer::parseMailItemFromGraph(const QJsonObject& mailJson) const
{
    // Esta función convertiría un objeto JSON de Microsoft Graph
    // a nuestro objeto MailItem
    
    // Por ahora, devolvemos un objeto vacío como stub
    return MailItem();
}

Folder OutlookSynchronizer::parseFolderFromGraph(const QJsonObject& folderJson) const
{
    // Esta función convertiría un objeto JSON de Microsoft Graph
    // a nuestro objeto Folder
    
    // Por ahora, devolvemos un objeto vacío como stub
    return Folder();
}
