const nodemailer = require("nodemailer");
const { getEnv } = require("../utils/envLoader");
const Setting = require("../models/setting.model");

const getTransporter = async () => {
    let auth = {
        user: getEnv("NODEMAILER_USER") || process.env.NODEMAILER_USER,
        pass: getEnv("NODEMAILER_PASS") || process.env.NODEMAILER_PASS
    };
    let service = "gmail";
    let host = undefined;
    let port = undefined;

    try {
        const settings = await Setting.getSettingsWithDecryption();
        if (settings && settings.email) {
            console.log("DEBUG: Using Email Credentials from System Settings");
            if (settings.email.user && settings.email.pass) {
                auth = {
                    user: settings.email.user,
                    pass: settings.email.pass
                };
            }

            if (settings.email.host) {
                host = settings.email.host;
                port = settings.email.port;
                service = undefined; // If host is provided, don't use service shorthand
            }
        }
    } catch (error) {
        console.error("Failed to fetch settings for email:", error);
    }

    const config = {};
    if (host) {
        config.host = host;
        config.port = port;
        config.secure = port === 465; // true for 465, false for other ports
    } else {
        config.service = service;
    }

    config.auth = auth;

    const maskUser = (u) => {
        if (!u) return 'Missing';
        const parts = u.split('@');
        if (parts.length < 2) return '***';
        return `${parts[0].substring(0, 3)}...@${parts[1]}`;
    };

    console.log(`DEBUG: Email Config - User: ${maskUser(auth.user)}, Host: ${host || 'Gmail Service'}`);

    return nodemailer.createTransport(config);
};

const sendMail = async (options) => {
    const transporter = await getTransporter();
    return await transporter.sendMail(options);
};

const getConfig = async () => {
    const settings = await Setting.getSettingsWithDecryption();
    return settings?.email || {
        user: getEnv("NODEMAILER_USER") || process.env.NODEMAILER_USER,
        host: undefined
    };
};

module.exports = { sendMail, getConfig };