#pragma once

#include "../synchronizer.h"
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
#include <QTimer>

class OutlookSynchronizer : public Synchronizer
{
    Q_OBJECT
public:
    explicit OutlookSynchronizer(QObject* parent = nullptr);
    ~OutlookSynchronizer() override = default;

    // Synchronizer interface
    bool initialize(const Account& account) override;
    bool syncFolder(const Folder& folder) override;
    QVector<Folder> getFolders() const override;
    QVector<MailItem> fetchMailItems(const QString& folderId, 
                                     qint64 sinceUid = 0) override;
    bool appendMailItem(const QString& folderId, const MailItem& item) override;
    bool updateMailItemFlags(const QString& folderId, 
                            const QString& itemUid,
                            bool read, bool flagged) override;
    bool deleteMailItem(const QString& folderId, 
                       const QString& itemUid) override;

signals:
    void folderSyncStarted(const QString& folderId);
    void folderSyncFinished(const QString& folderId, bool success);
    void mailItemAdded(const MailItem& item);
    void mailItemRemoved(const QString& itemUid);
    void mailItemUpdated(const MailItem& item);
    void errorOccurred(const QString& errorMessage);

private slots:
    void onGraphReplyFinished(QNetworkReply* reply);
    void onDeltaLinkTimer();

private:
    // Microsoft Graph API client
    QNetworkAccessManager* m_networkManager;
    
    // Authentication
    QString m_accessToken;
    QString m_refreshToken;
    QDateTime m_tokenExpires;
    
    // Delta sync tracking
    QMap<QString, QString> m_deltaLinks; // folderId -> deltaLink
    QTimer* m_deltaTimer;
    
    // Helper methods
    QString buildGraphUrl(const QString& endpoint) const;
    QNetworkRequest createAuthRequest(const QString& url) const;
    bool refreshAccessToken();
    QString getDeltaLink(const QString& folderId) const;
    void setDeltaLink(const QString& folderId, const QString& deltaLink);
    MailItem parseMailItemFromGraph(const QJsonObject& mailJson) const;
    Folder parseFolderFromGraph(const QJsonObject& folderJson) const;
};