#include <QtTest/QtTest>
#include <QFile>
#include <QStandardPaths>

#include "services/mimestorage.h"

class TestMimeStorage : public QObject
{
    Q_OBJECT
private slots:
    void storesRawMessageAndDecodedAttachments();
};

void TestMimeStorage::storesRawMessageAndDecodedAttachments()
{
    QStandardPaths::setTestModeEnabled(true);
    const QByteArray rawMime =
        "Message-ID: <mime-test@example.com>\r\n"
        "From: =?UTF-8?B?Sm9zw6k=?= <sender@example.com>\r\n"
        "To: receiver@example.com\r\n"
        "Subject: =?UTF-8?Q?Informe_de_prueba?=\r\n"
        "Date: Tue, 11 Aug 2026 12:00:00 +0000\r\n"
        "MIME-Version: 1.0\r\n"
        "Content-Type: multipart/mixed; boundary=\"wino-boundary\"\r\n"
        "\r\n"
        "--wino-boundary\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "Content-Transfer-Encoding: 8bit\r\n"
        "\r\n"
        "<p>Contenido completo</p>\r\n"
        "--wino-boundary\r\n"
        "Content-Type: application/octet-stream; name=\"datos.bin\"\r\n"
        "Content-Disposition: attachment; filename=\"datos.bin\"\r\n"
        "Content-Transfer-Encoding: base64\r\n"
        "\r\n"
        "AAECAwQF\r\n"
        "--wino-boundary--\r\n";

    MimeStorageService storage;
    ParsedMimeMessage parsed;
    QVERIFY(storage.parseMessage(rawMime, parsed));
    QCOMPARE(parsed.subject, QStringLiteral("Informe de prueba"));
    QCOMPARE(parsed.attachments.size(), 1);
    QCOMPARE(parsed.attachments.first().fileName, QStringLiteral("datos.bin"));
    QCOMPARE(parsed.attachments.first().data, QByteArray::fromHex("000102030405"));

    MailItem item;
    item.setMessageId(QStringLiteral("mime-test@example.com"));
    QVector<QString> attachmentPaths;
    QVERIFY(storage.storeMessage(QStringLiteral("account-test"), QStringLiteral("inbox"),
                                 item, rawMime, &attachmentPaths));
    QVERIFY(!item.fileId().isEmpty());
    QCOMPARE(storage.readEmlFile(item.fileId()), rawMime);
    QCOMPARE(item.attachments(), QVector<QString>{QStringLiteral("datos.bin")});
    QCOMPARE(attachmentPaths.size(), 1);

    QFile attachment(attachmentPaths.first());
    QVERIFY(attachment.open(QIODevice::ReadOnly));
    QCOMPARE(attachment.readAll(), QByteArray::fromHex("000102030405"));
    QVERIFY(storage.getEmlFilePath(item.fileId()).endsWith(QStringLiteral(".eml")));
}

QTEST_MAIN(TestMimeStorage)
#include "test_mimestorage.moc"
