// import nodemailer from 'nodemailer';


// const SMTP_HOST = process.env.SMTP_HOST;
// const SMTP_PORT = Number(process.env.SMTP_PORT || 587);
// const SMTP_USER = process.env.SMTP_USER;
// const SMTP_PASS = process.env.SMTP_PASS;
// const EMAIL_FROM = process.env.EMAIL_FROM;


// const transporter = nodemailer.createTransport({
//     host: process.env.SMTP_HOST,
//     port: Number(process.env.SMTP_PORT),
//     secure: Number(process.env.SMTP_PORT) === 465,
//     auth: process.env.SMTP_USER && process.env.SMTP_PASS ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
// });


// export async function sendEmail(to: string, subject: string, html: string) {
//     console.log(process.env.SMTP_HOST);

//     const info = await transporter.sendMail({
//         from: process.env.EMAIL_FROM,
//         to,
//         subject,
//         html,
//     });
//     return info;
// }

import nodemailer from "nodemailer";

export async function sendEmail(to: string, subject: string, html: string) {
    const host = process.env.SMTP_HOST;
    const port = process.env.SMTP_PORT ? Number(process.env.SMTP_PORT) : undefined;
    const user = process.env.SMTP_USER;
    const pass = process.env.SMTP_PASS;
    const from = `"Exam Infra Support" <${process.env.FROM_EMAIL || user}>`;

    // Validation
    if (!to || !to.includes("@")) {
        console.warn(`⚠️ Invalid recipient email: ${to}`);
        return { success: false, error: "Invalid recipient email address" };
    }

    if (!host || !port || !user || !pass || !from) {
        console.warn("⚠️ SMTP not configured — email not sent");
        return { success: false, error: "SMTP not configured on server" };
    }

    const transporter = nodemailer.createTransport({
        host,
        port,
        secure: port === 465,
        auth: { user, pass },
    });

    try {
        await transporter.sendMail({ from, to, subject, html });
        console.log(`✅ Email sent to ${to}`);
        return { success: true };
    } catch (err: any) {
        console.error("❌ Failed to send email:", err);
        return { success: false, error: err?.message || "Failed to send email" };
    }
}
