#ifndef MIMESTORAGESERVICE_H
#define MIMESTORAGESERVICE_H

#include <QObject>
#include <QString>
#include <QDir>
#include <QFile>
#include <QByteArray>
#include <QVector>
#include "core/mailitem.h"

struct ParsedMimeAttachment
{
    QString fileName;
    QString mimeType;
    QString contentId;
    QByteArray data;
};

struct ParsedMimeMessage
{
    QString messageId;
    QString subject;
    QString from;
    QString to;
    QString cc;
    QString bcc;
    QDateTime date;
    QString bodyHtml;
    QVector<ParsedMimeAttachment> attachments;
};

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

    QString saveEmlFile(const QString &accountId, const QString &folderId, const MailItem &mail);
    QString saveRawEmlFile(const QString &accountId, const QString &folderId,
                           const QByteArray &rawMime, const QString &stableId = QString());
    bool storeMessage(const QString &accountId, const QString &folderId,
                      MailItem &mail, const QByteArray &rawMime,
                      QVector<QString> *storedAttachmentPaths = nullptr);
    bool parseMessage(const QByteArray &rawMime, ParsedMimeMessage &message) const;
    QString getEmlFilePath(const QString &fileId) const;
    QByteArray readEmlFile(const QString &fileId) const;
    bool deleteEmlFile(const QString &fileId);

    QStringList listAttachments(const QString &mailItemId) const;
    QString saveAttachment(const QString &fileId, const QString &fileName,
                           const QByteArray &data);

private:
    QString storagePath() const;
    QString ensureDirectory(const QString &path) const;
    QString safeComponent(const QString &value) const;
    QString decodeHeaderValue(const QString &value) const;
    QByteArray decodeTransfer(const QByteArray &data, const QString &encoding) const;
    void parseMimePart(const QByteArray &part, ParsedMimeMessage &message,
                       QString *plainText, QString *htmlText) const;
};

#endif // MIMESTORAGESERVICE_H
