// import nodemailer from 'nodemailer';
// import dotenv from 'dotenv';
// import { Settings } from '../models/index.js';

// dotenv.config();

// const normalizeBoolean = (value) => {
//     if (typeof value === 'boolean') return value;
//     if (typeof value === 'string') {
//         return ['true', '1', 'yes', 'on'].includes(value.toLowerCase());
//     }
//     return Boolean(value);
// };

// const getMailConfig = async () => {
//     let settings = null;

//     try {
//         settings = await Settings.findOne();
//     } catch (error) {
//         settings = null;
//     }

//     const envHost = process.env.SMTP_HOST || process.env.EMAIL_HOST || '';
//     const envPort = Number(process.env.SMTP_PORT || process.env.EMAIL_PORT || 465);
//     const envSecure = normalizeBoolean(process.env.SMTP_SECURE ?? process.env.EMAIL_SECURE ?? true);
//     const envUser = process.env.SMTP_USER || process.env.EMAIL_USER || '';
//     const envPass = process.env.SMTP_PASS || process.env.EMAIL_PASS || '';

//     const authUser = settings?.smtp_user || envUser;
//     const authPass = settings?.smtp_pass || envPass;

//     return {
//         host: settings?.smtp_host || envHost || 'smtp.gmail.com',
//         port: settings?.smtp_port || envPort || 465,
//         secure: settings?.smtp_secure !== undefined ? normalizeBoolean(settings.smtp_secure) : (envSecure || true),
//         auth: {
//             user: authUser,
//             pass: authPass,
//         },
//         fromEmail: settings?.smtp_from_email || authUser,
//         fromName: settings?.smtp_from_name || ''
//     };
// };

// // const createTransporter = async () => {
// //     const config = await getMailConfig();

// //     return nodemailer.createTransport({
// //         host: config.host,
// //         port: config.port,
// //         secure: config.secure,
// //         auth: config.auth,
// //         tls: {
// //             rejectUnauthorized: false
// //         }
// //     });
// // };


// const createTransporter = async () => {
//     const config = await getMailConfig();

//     if (!config.auth.user || !config.auth.pass) {
//         throw new Error('SMTP credentials missing');
//     }

//     return nodemailer.createTransport({
//         host: config.host,
//         port: Number(config.port),
//         secure: Number(config.port) === 465,
//         auth: {
//             user: config.auth.user,
//             pass: config.auth.pass
//         }
//     });
// };
// const transporter = {
//     async sendMail(options) {
//         const transport = await createTransporter();
//         return transport.sendMail(options);
//     },
//     verify(callback) {
//         if (typeof callback === 'function') {
//             createTransporter()
//                 .then((transport) => transport.verify())
//                 .then(() => callback(null, true))
//                 .catch((error) => callback(error, false));
//             return;
//         }

//         return createTransporter().then((transport) => transport.verify());
//     }
// };

// export const getTransporter = createTransporter;
// export { getMailConfig };
// export default transporter;



import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
import { Settings } from '../models/index.js';

dotenv.config();

const normalizeBoolean = (value) => {
    if (typeof value === 'boolean') return value;
    if (typeof value === 'string') {
        return ['true', '1', 'yes', 'on'].includes(value.toLowerCase());
    }
    return Boolean(value);
};

const getMailConfig = async () => {
    let settings = null;

    try {
        settings = await Settings.findOne();
    } catch (error) {
        settings = null;
    }

    const envHost = process.env.SMTP_HOST || process.env.EMAIL_HOST || '';
    const envPort = Number(process.env.SMTP_PORT || process.env.EMAIL_PORT || 465);
    const envSecure = normalizeBoolean(process.env.SMTP_SECURE ?? process.env.EMAIL_SECURE ?? true);

    // .trim() added — admin panel se copy-paste karte waqt aksar
    // trailing/leading space aa jata hai jo silently auth fail kar deta hai
    const envUser = (process.env.SMTP_USER || process.env.EMAIL_USER || '').trim();
    const envPass = (process.env.SMTP_PASS || process.env.EMAIL_PASS || '').trim();

    const authUser = (settings?.smtp_user || envUser || '').trim();
    const authPass = (settings?.smtp_pass || envPass || '').trim();

    const port = Number(settings?.smtp_port || envPort || 465);

    // secure ab DB ke smtp_secure field ko respect karta hai
    // (port 465 ke liye fallback true rehta hai agar field set nahi hai)
    const secure = settings?.smtp_secure !== undefined
        ? normalizeBoolean(settings.smtp_secure)
        : (envSecure !== undefined ? envSecure : port === 465);

    return {
        host: (settings?.smtp_host || envHost || 'smtp.gmail.com').trim(),
        port,
        secure,
        auth: {
            user: authUser,
            pass: authPass,
        },
        fromEmail: (settings?.smtp_from_email || authUser || '').trim(),
        fromName: settings?.smtp_from_name || ''
    };
};

const createTransporter = async () => {
    const config = await getMailConfig();

    if (!config.auth.user || !config.auth.pass) {
        throw new Error('SMTP credentials missing');
    }

    return nodemailer.createTransport({
        host: config.host,
        port: config.port,
        secure: config.secure,
        auth: {
            user: config.auth.user,
            pass: config.auth.pass
        },
        // self-signed / mismatched cert wale shared hosting SMTP servers
        // ke liye — agar tumhara provider valid trusted cert deta hai
        // to ye line hata sakte ho
        tls: {
            rejectUnauthorized: false
        }
    });
};

const transporter = {
    async sendMail(options) {
        const transport = await createTransporter();
        return transport.sendMail(options);
    },
    verify(callback) {
        if (typeof callback === 'function') {
            createTransporter()
                .then((transport) => transport.verify())
                .then(() => callback(null, true))
                .catch((error) => callback(error, false));
            return;
        }

        return createTransporter().then((transport) => transport.verify());
    }
};

export const getTransporter = createTransporter;
export { getMailConfig };
export default transporter;