#include "accountsetupdialoglauncher.h"
#include <QDebug>

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

void AccountSetupDialogLauncher::launchSetupDialog()
{
    emit accountSetupStarted();
    qDebug() << "[AccountSetupDialogLauncher] Dialog would launch here (Fase 3)";
}

void AccountSetupDialogLauncher::setupAccountManually(const Account &account)
{
    qDebug() << "[AccountSetupDialogLauncher] Setting up account:" << account.email();

    // Save to database
    bool created = AccountDao::insert(account);
    if (!created) {
        qWarning() << "[AccountSetupDialogLauncher] Failed to save account to DB";
        emit accountSetupFailed("Failed to save account");
        return;
    }

    // Initialize synchronizer
    initializeSynchronizer(account);

    // Publish event
    WinoMail::Events::AccountAddedEvent event;
    event.account = account;
    EVENT_BUS.publish(event);

    qDebug() << "[AccountSetupDialogLauncher] Account created successfully:" << account.email();
    emit accountSetupCompleted(account);
}

void AccountSetupDialogLauncher::initializeSynchronizer(const Account &account)
{
    QString accountId = QString::number(account.id());
    
    // Determine provider type from Account's access token or type
    QString providerType;
    switch (account.type()) {
        case AccountType::Gmail:
            providerType = "gmail";
            break;
        case AccountType::Outlook:
            providerType = "outlook";
            break;
        case AccountType::IMAP:
            providerType = "imap";
            break;
        default:
            providerType = "imap";
            break;
    }
    
    Synchronizer *sync = SynchronizerProvider::instance().createSynchronizer(accountId, providerType);
    if (sync) {
        sync->initialize(account);
        qDebug() << "[AccountSetupDialogLauncher] Synchronizer initialized for account:" << accountId;
    } else {
        qWarning() << "[AccountSetupDialogLauncher] Could not create synchronizer for:" << providerType;
    }
}

#include "accountsetupdialoglauncher.moc"
