import nodemailer from 'nodemailer';

type SendMailOptions = {
  to: string;
  subject: string;
  text: string;
  html: string;
};

export async function sendEmail({ to, subject, text, html }: SendMailOptions) {
  const smtpHost = process.env.SMTP_HOST;
  const smtpUser = process.env.SMTP_USER;
  const smtpPassword = process.env.SMTP_PASSWORD;
  const smtpPort = Number(process.env.SMTP_PORT) || 587;
  const useTls = (process.env.EMAIL_USE_TLS || process.env.SMTP_USE_TLS || 'true').toLowerCase() === 'true';

  console.log(`[Email Service] Preparing email for: ${to}`);
  
  if (!smtpHost || !smtpUser || !smtpPassword) {
    console.warn('[Email Service] SMTP configuration is missing in .env.local.');
    console.log(`------ LOGGED EMAIL START ------\nTo: ${to}\nSubject: ${subject}\nText:\n${text}\n------ LOGGED EMAIL END ------`);
    return { success: true, logged: true };
  }

  try {
    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      secure: smtpPort === 465,
      requireTLS: useTls,
      auth: {
        user: smtpUser,
        pass: smtpPassword,
      },
    });

    const mailOptions = {
      from: { name: 'CodeframeAI Team', address: smtpUser },
      to,
      subject,
      text,
      html,
    };

    const info = await transporter.sendMail(mailOptions);
    console.log(`[Email Service] Email sent successfully: ${info.messageId}`);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error('[Email Service] Error sending email:', error);
    return { success: false, error };
  }
}
