#pragma once

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

class GmailSynchronizer : public Synchronizer
{
    Q_OBJECT
public:
    explicit GmailSynchronizer(QObject* parent = nullptr);
    ~GmailSynchronizer() 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 onGmailReplyFinished(QNetworkReply* reply);
    void onHistoryTimer();

private:
    // Gmail API client
    QNetworkAccessManager* m_networkManager;
    
    // Authentication
    QString m_accessToken;
    QString m_refreshToken;
    QDateTime m_tokenExpires;
    
    // History tracking for incremental sync
    QMap<QString, qint64> m_historyIds; // folderId -> historyId
    QTimer* m_historyTimer;
    
    // Helper methods
    QString buildGmailUrl(const QString& endpoint) const;
    QNetworkRequest createAuthRequest(const QString& url) const;
    bool refreshAccessToken();
    qint64 getHistoryId(const QString& folderId) const;
    void setHistoryId(const QString& folderId, qint64 historyId);
    MailItem parseMailItemFromGmail(const QJsonObject& mailJson) const;
    Folder parseFolderFromGmail(const QJsonObject& labelJson) const;
    QStringList extractHeaderValue(const QJsonArray& headers, const QString& name) const;
};