#include <QtTest/QtTest>
#include "../../src/db/dao/accountdao.h"
#include "../../src/db/databasemanager.h"
#include "../../src/core/models/account.h"

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

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

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

void TestAccountDao::testInsertAndFind()
{
    Account account;
    account.setEmail("test@example.com");
    account.setProvider("IMAP");
    account.setHost("imap.example.com");
    account.setPort(993);
    account.setUsername("testuser");
    account.setPassword("testpass");
    account.setUseSsl(true);

    bool inserted = AccountDao::insert(account);
    QVERIFY(inserted);
    QVERIFY(account.id() > 0);

    Account found = AccountDao::findById(account.id());
    QVERIFY(found.isValid());
    QCOMPARE(found.email(), QString("test@example.com"));
    QCOMPARE(found.provider(), QString("IMAP"));
    QCOMPARE(found.host(), QString("imap.example.com"));
    QCOMPARE(found.port(), 993);
    QCOMPARE(found.username(), QString("testuser"));
    QCOMPARE(found.password(), QString("testpass"));
    QVERIFY(found.useSsl());
}

void TestAccountDao::testUpdate()
{
    Account account;
    account.setEmail("original@example.com");
    account.setProvider("IMAP");
    account.setHost("imap.example.com");
    account.setPort(993);
    account.setUsername("user");
    account.setPassword("pass");
    account.setUseSsl(true);

    bool inserted = AccountDao::insert(account);
    QVERIFY(inserted);
    qint64 id = account.id();

    account.setEmail("updated@example.com");
    account.setProvider("Gmail");
    account.setUseSsl(false);

    bool updated = AccountDao::update(account);
    QVERIFY(updated);

    Account found = AccountDao::findById(id);
    QVERIFY(found.isValid());
    QCOMPARE(found.email(), QString("updated@example.com"));
    QCOMPARE(found.provider(), QString("Gmail"));
    QVERIFY(!found.useSsl());
}

void TestAccountDao::testRemove()
{
    Account account;
    account.setEmail("todelete@example.com");
    account.setProvider("IMAP");
    account.setHost("imap.example.com");
    account.setPort(993);
    account.setUsername("user");
    account.setPassword("pass");
    account.setUseSsl(true);

    bool inserted = AccountDao::insert(account);
    QVERIFY(inserted);
    qint64 id = account.id();

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

    Account found = AccountDao::findById(id);
    QVERIFY(!found.isValid());
}

QTEST_MAIN(TestAccountDao)
#include "test_accountdao.moc"
