#include <QtTest/QtTest>
#include "../../src/db/dao/folderdao.h"
#include "../../src/db/databasemanager.h"
#include "../../src/core/models/folder.h"

class TestFolderDao : public QObject
{
    Q_OBJECT
private slots:
    void initTestCase();
    void cleanupTestCase();
    void testInsertAndFind();
    void testUpdate();
    void testRemove();
};

void TestFolderDao::initTestCase()
{
    DatabaseManager::instance().openDatabase(":memory:");
    DatabaseManager::instance().createTables();
}

void TestFolderDao::cleanupTestCase()
{
    DatabaseManager::instance().closeDatabase();
}

void TestFolderDao::testInsertAndFind()
{
    Folder folder;
    folder.setAccountId(1);
    folder.setName("Inbox");
    folder.setPath("INBOX");
    folder.setIsInbox(true);

    bool inserted = FolderDao::insert(folder);
    QVERIFY(inserted);
    QVERIFY(folder.id() > 0);

    Folder found = FolderDao::findById(folder.id());
    QVERIFY(found.isValid());
    QCOMPARE(found.accountId(), 1);
    QCOMPARE(found.name(), QString("Inbox"));
    QCOMPARE(found.path(), QString("INBOX"));
    QVERIFY(found.isInbox());
}

void TestFolderDao::testUpdate()
{
    Folder folder;
    folder.setAccountId(1);
    folder.setName("Drafts");
    folder.setPath("Drafts");
    folder.setIsInbox(false);

    bool inserted = FolderDao::insert(folder);
    QVERIFY(inserted);
    qint64 id = folder.id();

    folder.setName("Updated Drafts");
    folder.setPath("Updated/Drafts");

    bool updated = FolderDao::update(folder);
    QVERIFY(updated);

    Folder found = FolderDao::findById(id);
    QVERIFY(found.isValid());
    QCOMPARE(found.name(), QString("Updated Drafts"));
    QCOMPARE(found.path(), QString("Updated/Drafts"));
}

void TestFolderDao::testRemove()
{
    Folder folder;
    folder.setAccountId(1);
    folder.setName("ToDelete");
    folder.setPath("ToDelete");
    folder.setIsInbox(false);

    bool inserted = FolderDao::insert(folder);
    QVERIFY(inserted);
    qint64 id = folder.id();

    bool removed = FolderDao::remove(id);
    QVERIFY(removed);

    Folder found = FolderDao::findById(id);
    QVERIFY(!found.isValid());
}

QTEST_MAIN(TestFolderDao)
#include "test_folderdao.moc"
