#include "mimestorage.h"
#include <QStandardPaths>
#include <QDebug>
#include <QUuid>

MimeStorageService::MimeStorageService(QObject *parent)
    : QObject(parent)
{
}

QString MimeStorageService::storagePath() const
{
    QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/mails";
    return ensureDirectory(path);
}

QString MimeStorageService::ensureDirectory(const QString &path) const
{
    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    return dir.absolutePath();
}

QString MimeStorageService::saveEmlFile(const QString &accountId, const QString &folderId, const MailItem &mail)
{
    QString dir = storagePath() + "/" + accountId + "/" + folderId;
    ensureDirectory(dir);

    QString fileName = mail.messageId();
    if (fileName.isEmpty()) {
        fileName = QUuid::createUuid().toString(QUuid::WithoutBraces);
    }
    fileName.replace('/', '_').replace('\\', '_');
    QString filePath = dir + "/" + fileName + ".eml";

    // Write a basic .eml structure
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream stream(&file);
        stream << "From: " << mail.sender() << "\r\n";
        stream << "To: " << mail.recipient() << "\r\n";
        stream << "Subject: " << mail.subject() << "\r\n";
        stream << "Date: " << mail.date().toString(Qt::RFC2822Date) << "\r\n";
        stream << "MIME-Version: 1.0\r\n";
        stream << "Content-Type: text/html; charset=UTF-8\r\n";
        stream << "\r\n";
        stream << mail.bodyHtml() << "\r\n";
        file.close();
        qDebug() << "[MimeStorage] Saved .eml:" << filePath;
        return fileName;
    }
    qWarning() << "[MimeStorage] Failed to save .eml:" << filePath;
    return QString();
}

QString MimeStorageService::getEmlFilePath(const QString &fileId) const
{
    // Search in all account/folder directories (simplified)
    QDir baseDir(storagePath());
    QStringList filters;
    filters << fileId + ".eml";
    
    QFileInfoList files = baseDir.entryInfoList(filters, QDir::Files, QDir::Name);
    for (const auto &info : files) {
        QStringList parts = info.absoluteFilePath().split('/');
        if (parts.size() >= 2) {
            return info.absoluteFilePath();
        }
    }
    return QString();
}

QByteArray MimeStorageService::readEmlFile(const QString &fileId) const
{
    QString path = getEmlFilePath(fileId);
    if (path.isEmpty()) return {};

    QFile file(path);
    if (file.open(QIODevice::ReadOnly)) {
        return file.readAll();
    }
    return {};
}

bool MimeStorageService::deleteEmlFile(const QString &fileId)
{
    QString path = getEmlFilePath(fileId);
    if (path.isEmpty()) return false;
    return QFile::remove(path);
}

QStringList MimeStorageService::listAttachments(const QString &mailItemId) const
{
    Q_UNUSED(mailItemId);
    // TODO: Parse .eml to get attachments when GMime is available
    return {};
}

bool MimeStorageService::saveAttachment(const QString &mailItemId, const QString &fileName, const QByteArray &data)
{
    Q_UNUSED(mailItemId);
    QString dir = storagePath() + "/attachments";
    ensureDirectory(dir);
    
    QFile file(dir + "/" + fileName);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        return true;
    }
    return false;
}

#include "mimestorage.moc"
