import nodemailer from "nodemailer";
import { loadSystemConfig } from "./system-config";

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

export async function sendEmail(opts: {
  to: string;
  subject: string;
  html: string;
  attachments?: EmailAttachment[];
}) {
  const cfg = await loadSystemConfig();
  if (!cfg.email?.enabled || !cfg.email?.smtp?.host || !cfg.email?.smtp?.port || !cfg.email?.from) {
    return { ok: false, message: "Email not configured" };
  }

  const transporter = nodemailer.createTransport({
    host: cfg.email.smtp.host,
    port: cfg.email.smtp.port,
    secure: false,
    auth: cfg.email.smtp.user
      ? { user: cfg.email.smtp.user, pass: cfg.email.smtp.pass }
      : undefined,
  });

  await transporter.sendMail({
    from: cfg.email.from,
    to: opts.to,
    subject: opts.subject,
    html: opts.html,
    attachments: opts.attachments,
  });

  return { ok: true };
}
