import {
  createTransport,
  // createTestAccount,
  type SendMailOptions,
} from "nodemailer";
import { Eta } from "eta";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const eta = new Eta({
  views: join(__dirname, "./"),
  useWith: true,
});

// const account = await createTestAccount();
const transport = createTransport({
  host: import.meta.env.SMTP_SERVER!,
  port: import.meta.env.SMTP_PORT!,
  secure: import.meta.env.SMTP_SECURE!,
  auth: {
    // TODO: replace `user` and `pass` values from <https://forwardemail.net>
    user: import.meta.env.SMTP_USERNAME!,
    pass: import.meta.env.SMTP_PASSWORD!,
  },
});

type Email = SendMailOptions & {
  template?: string;
  data?: Record<string, any>;
};

export const sendEmail = async ({
  data = {},
  template = "welcome",
  ...rest
}: Email) => {
  const subject = rest.subject ?? "WELCOME";
  const from = `Sambekiel & Co Resources <${
    rest.from ?? import.meta.env.SMTP_USERNAME!
  }>`;
  const to = rest.to ?? import.meta.env.SMTP_EMAIL!;
  const replyTo = rest.replyTo ?? rest.from ?? import.meta.env.SMTP_EMAIL!;

  const html = await eta.renderAsync(template, {
    ...data,
    subject,
  });
  const text = html
    .replace(/<head[^>]*>.*?<\/head>/gis, "")
    .replace(/<[^>]*>?/gm, "");

  return await transport.sendMail({ ...rest, text, html, from, to, replyTo });
};

export const sendMultipleMail = async ({
  messages,
  template,
}: {
  messages: Email[];
  template?: string;
}) => {
  return await Promise.all([
    messages.map((msg) => sendEmail({ ...msg, template })),
  ]);
};
