import { MailtrapClientConfig, MailtrapTransport } from 'mailtrap';
import nodemailer from 'nodemailer';

const TOKEN = Bun.env.MAILTRAP_API_TOKEN;

let cachedTransporter: ReturnType<typeof nodemailer.createTransport> | null = null;

function getTransporter() {
  if (cachedTransporter) return cachedTransporter;

  if (!TOKEN) {
    throw new Error('Missing MAILTRAP_API_TOKEN env var.');
  }

  const config: MailtrapClientConfig = {
    token: TOKEN,
    sandbox: Bun.env.MAIL_SANDBOX === 'true',
    testInboxId: Bun.env.MAIL_INBOX_ID ? Number(Bun.env.MAIL_INBOX_ID) : undefined,
  };

  console.log(JSON.stringify(config, null, 2));

  cachedTransporter = nodemailer.createTransport(MailtrapTransport(config));
  return cachedTransporter;
}

export async function sendMail(input: {
  to: string;
  subject: string;
  html: string;
  text: string;
}) {
  const smtpFrom = Bun.env.SMTP_FROM;

  if (!smtpFrom) {
    throw new Error('Missing SMTP_FROM env var.');
  }

  await getTransporter().sendMail({
    from: smtpFrom,
    to: input.to,
    subject: input.subject,
    html: input.html,
    text: input.text,
  });
}
