import nodemailer from "nodemailer";

function buildTransport() {
  if (process.env.DRY_RUN === "true") {
    return nodemailer.createTransport({ jsonTransport: true });
  }

  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT || 465),
    secure: process.env.SMTP_SECURE !== "false",
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });
}

const transporter = buildTransport();

export type OutgoingAttachment = {
  filename: string;
  content: Buffer;
  contentType?: string;
};

export async function sendMail(params: {
  to: string;
  subject: string;
  text: string;
  attachments?: OutgoingAttachment[];
}) {
  const info = await transporter.sendMail({
    from: `"${process.env.FROM_NAME}" <${process.env.FROM_EMAIL}>`,
    replyTo: process.env.FROM_EMAIL, // replies land back in info@, as required
    to: params.to,
    subject: params.subject,
    text: params.text,
    attachments: params.attachments,
  });
  return info;
}
