import nodemailer from "nodemailer";

type MailPayload = {
  to: string;
  subject: string;
  text: string;
};

const hasSmtpConfig = () =>
  Boolean(
    process.env.SMTP_HOST &&
      process.env.SMTP_PORT &&
      process.env.SMTP_USER &&
      process.env.SMTP_PASS
  );

export async function sendMail(payload: MailPayload) {
  if (!hasSmtpConfig()) {
    // Fallback for dev: log instead of sending.
    console.log("[mail]", payload.subject, payload.text);
    return;
  }

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === "true",
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS
    }
  });

  await transporter.sendMail({
    from: process.env.SMTP_FROM || process.env.SMTP_USER,
    to: payload.to,
    subject: payload.subject,
    text: payload.text
  });
}
