#pragma once

#include "../synchronizer.h"
#include <QObject>
#include <QStringList>
#include "imapconnection.h"

class ImapSynchronizer : public Synchronizer
{
    Q_OBJECT
public:
    explicit ImapSynchronizer(QObject* parent = nullptr);
    ~ImapSynchronizer() 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 progressChanged(int percent) const;
    void statusMessage(const QString& message) const;

private:
    QVector<qint64> parseUidSearchResponse(const QString& response) const;
    // Connection details (set by initialize)
    mutable QString m_host;
    mutable quint16 m_port{0};
    mutable bool m_useSsl{false};
    mutable QString m_username;
    mutable QString m_password;
    mutable QString m_authMethod; // "plain" or "oauth2"

    // Helper para generar IDs únicos de eventos
    QString generateEventId() const;

    // Helper: conecta y loguea al servidor (reutilizable)
    bool connectAndLogin(ImapConnection &conn) const;

    // IMAP response parsers
    QVector<Folder> parseListResponse(const QStringList& lines) const;
    QVector<MailItem> parseFetchResponse(const QStringList& lines) const;
    QVector<MailItem> parseFetchResponseBytes(const QByteArray& response) const;
    bool persistFetchedItem(const Folder& folder, MailItem& item) const;
    
    // Sync folder helpers
    QVector<qint64> fetchAllUids(const QString& folderId) const;
    void parseAndUpdateFlags(const QByteArray& response, int folderId) const;
};
