import nodemailer from "nodemailer";
import { getResolvedMailConfiguration } from "./mailSettings";

type SendMailInput = {
  to: string[];
  subject: string;
  text: string;
  html?: string;
  replyTo?: string;
  fromName?: string;
  attachments?: Array<{
    filename: string;
    content: Buffer;
    contentType?: string;
  }>;
};

export async function canSendOperationalEmails() {
  const { config } = await getResolvedMailConfiguration();
  return config.ready;
}

export async function sendOperationalEmail(input: SendMailInput): Promise<{ sent: boolean; reason?: string }> {
  const { config } = await getResolvedMailConfiguration();
  if (!config.ready) {
    return {
      sent: false,
      reason: config.missing.length > 0
        ? `Configuration SMTP incomplète: ${config.missing.join(", ")}`
        : "SMTP non configuré",
    };
  }

  const transporter = nodemailer.createTransport({
    host: config.host,
    port: Number(config.port),
    secure: config.secure,
    requireTLS: config.requireTLS,
    auth: config.user && config.pass
      ? {
          user: config.user,
          pass: config.pass,
        }
      : undefined,
  });

  await transporter.sendMail({
    from: input.fromName ? `${input.fromName} <${config.from}>` : config.from,
    to: input.to.join(", "),
    replyTo: input.replyTo,
    subject: input.subject,
    text: input.text,
    html: input.html,
    attachments: input.attachments,
  });

  return { sent: true };
}
