const nodemailer = require('nodemailer');
const { SystemSetting } = require('../models/settings');
const { EmailLog } = require('../models/foundation');
const { decrypt } = require('../utils/crypto');

const getEmailTransporter = async () => {
    const settings = await SystemSetting.findAll();
    const config = {};
    settings.forEach(s => config[s.key] = s.value);

    if (!config.EMAIL_HOST || !config.EMAIL_USER) {
        throw new Error('Email settings are not configured');
    }

    const transporter = nodemailer.createTransport({
        host: config.EMAIL_HOST,
        port: parseInt(config.EMAIL_PORT) || 587,
        secure: config.EMAIL_ENCRYPTION === 'SSL',
        auth: {
            user: config.EMAIL_USER,
            pass: decrypt(config.EMAIL_PASSWORD)
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    return { transporter, senderName: config.EMAIL_SENDER_NAME, senderEmail: config.EMAIL_USER };
};

exports.sendEmail = async ({ to, subject, html, text, attachments, module, referenceId }) => {
    try {
        const { transporter, senderName, senderEmail } = await getEmailTransporter();

        const mailOptions = {
            from: `"${senderName || 'Finance System'}" <${senderEmail}>`,
            to,
            subject,
            text,
            html,
            attachments
        };

        const info = await transporter.sendMail(mailOptions);

        // Log the success
        await EmailLog.create({
            to,
            subject,
            module,
            referenceId,
            status: 'Success'
        });

        console.log('Email sent: %s', info.messageId);
        return info;
    } catch (err) {
        // Log the failure
        await EmailLog.create({
            to,
            subject,
            module,
            referenceId,
            status: 'Failed',
            errorMessage: err.message
        });

        console.error('Email send error:', err);
        throw err;
    }
};

exports.testConnection = async () => {
    try {
        const { transporter } = await getEmailTransporter();
        await transporter.verify();
        return true;
    } catch (err) {
        console.error('Email verification failed:', err);
        throw err;
    }
};
