import { createTransport } from "nodemailer";
import SMTPTransport from "nodemailer/lib/smtp-transport";

import type { Options } from "nodemailer/lib/mailer";

interface Email {
  email: string;
  message: string;
  html?: string;
  subject: string;
  name: string;
}

export function constructEmailHtml(props: Email) {
  return `<div>${props.message}</div>`;
}

export default async function (props: Email) {
  const transporter = createTransport({
    host: process.env.EMAIL_HOST || import.meta.env.EMAIL_HOST,
    port: process.env.EMAIL_PORT || import.meta.env.EMAIL_PORT,
    secure:
      process.env.EMAIL_SECURE === "true" ||
      import.meta.env.EMAIL_SECURE === "true",
    auth: {
      user: process.env.EMAIL_USER || import.meta.env.EMAIL_USER,
      pass: process.env.EMAIL_PASS || import.meta.env.EMAIL_PASS
    }
  } as SMTPTransport.Options);

  if (!props.html) {
    props.html = constructEmailHtml(props);
  }

  const message: Options = {
    from: `${props.name} (Website) <${process.env.EMAIL_FROM || import.meta.env.EMAIL_FROM}>`,
    to: "nathan@nathancummins.com.au",
    replyTo: props.email,
    subject: props.subject,
    text: props.message,
    html: props.html
  };

  const info = await transporter.sendMail(message);
  return info;
}
