#include "mailservice.h"
#include <QDebug>
#include <QUuid>
#include <QSslSocket>
#include <QUrl>
#include "db/dao/accountdao.h"

static void sendViaSmtp(const MailItem &mail, const Account &account);

MailService::MailService(QObject *parent)
    : QObject(parent)
    , m_composer(new EmailComposerBridge(this))
{
}

QVector<MailItem> MailService::getMails(const QString &folderId)
{
    return MailItemDao::findByFolderId(folderId.toInt());
}

void MailService::sendMail(const MailItem &mail, const QString &accountId)
{
    qDebug() << "[MailService] Sending mail:" << mail.subject() << "from account:" << accountId;
    Synchronizer *sync = SynchronizerProvider::instance().getSynchronizer(accountId);
    if (!sync) {
        emit mailSendFailed(mail.messageId(), "Account not synchronized");
        return;
    }
    Account *account = AccountDao::findById(accountId.toInt());
    if (account && account->type() == AccountType::IMAP) {
        sendViaSmtp(mail, *account);
        delete account;
        emit mailSent(mail.messageId());
        return;
    }
    if (account) delete account;
    MailItem copy = mail;
    copy.setFolderId(5);
    MailItemDao::insert(copy);
    emit mailSent(mail.messageId());
}

void MailService::fetchMails(const QString &accountId, const QString &folderId)
{
    Synchronizer *sync = SynchronizerProvider::instance().getSynchronizer(accountId);
    if (!sync) { qWarning() << "[MailService] No synchronizer"; return; }
    QVector<MailItem> items = sync->fetchMailItems(folderId);
    emit mailFetched(accountId, folderId, items);
}

void MailService::moveMail(const QString &mailItemId, const QString &targetFolderId)
{
    qDebug() << "[MailService] Moving mail:" << mailItemId;
    std::optional<MailItem> item = MailItemDao::findById(mailItemId.toLongLong());
    if (item.has_value()) {
        MailItem m = item.value();
        m.setFolderId(targetFolderId.toInt());
        MailItemDao::update(m);
    }
    emit mailMoved(mailItemId);
}

void MailService::deleteMail(const QString &mailItemId)
{
    MailItemDao::remove(mailItemId.toLongLong());
    emit mailDeleted(mailItemId);
}

void MailService::markAsRead(const QString &mailItemId, bool read)
{
    std::optional<MailItem> item = MailItemDao::findById(mailItemId.toLongLong());
    if (item.has_value()) {
        MailItem m = item.value();
        m.setRead(read);
        MailItemDao::update(m);
    }
    emit mailReadStateChanged(mailItemId, read);
}

static void sendViaSmtp(const MailItem &mail, const Account &account)
{
    Q_UNUSED(mail); Q_UNUSED(account);
    qDebug() << "[MailService] SMTP not implemented (requires GMime)";
}

#include "mailservice.moc"