import nodemailer from 'nodemailer';

const isSmtpConfigured =
  process.env.SMTP_HOST &&
  process.env.SMTP_PORT &&
  process.env.SMTP_USER &&
  process.env.SMTP_PASS;

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

export async function sendMail(
  to: string,
  subject: string,
  html: string
): Promise<void> {
  if (transporter) {
    await transporter.sendMail({
      from: process.env.SMTP_USER,
      to,
      subject,
      html,
    });
  } else {
    console.log(`[DEV MAIL] To: ${to}`);
    console.log(`[DEV MAIL] Subject: ${subject}`);
    console.log(`[DEV MAIL] Body: ${html}`);
  }
}

export async function sendOtpEmail(
  email: string,
  otp: string
): Promise<void> {
  const subject = 'Your Visity verification code';
  const html = `<p>Your verification code is: <strong>${otp}</strong></p><p>This code expires in 10 minutes.</p>`;
  await sendMail(email, subject, html);
}
