// Abstraction sendMail : seul point d'entree pour envoyer un email depuis le
// projet. Wrappe nodemailer + logging + erreurs typees.
//
// Usage :
//   import { sendMail } from "@/lib/email/send";
//   await sendMail({ to: "x@y.fr", subject: "...", html: "...", text: "..." });

import "server-only";
import { getTransporter, getFromAddress } from "./client";

export type SendMailInput = {
  to: string | string[];
  subject: string;
  /** Corps HTML (recommande, gere les clients mail modernes). */
  html: string;
  /** Corps texte brut (obligatoire, fallback + meilleur deliverability score). */
  text: string;
  /** Reply-To optionnel (utile pour les notifs contact : on repond au prospect). */
  replyTo?: string;
  /** From overrides (rare ; par defaut SMTP_FROM_NAME + SMTP_FROM_EMAIL). */
  from?: string;
};

export type SendMailResult =
  | { ok: true; messageId: string }
  | { ok: false; error: string };

/**
 * Envoie un email via le transporter SMTP. Retourne un resultat typed plutot
 * que de throw : les call sites (server actions) doivent decider quoi faire en
 * cas d'echec sans crash.
 */
export async function sendMail(input: SendMailInput): Promise<SendMailResult> {
  try {
    const transporter = getTransporter();
    const info = await transporter.sendMail({
      from: input.from ?? getFromAddress(),
      to: input.to,
      replyTo: input.replyTo,
      subject: input.subject,
      text: input.text,
      html: input.html,
      // Headers utiles : List-Unsubscribe (mailto:) ameliore le score deliverability
      // sur les notifs marketing. Pas applicable ici (transactionnel).
    });
    return { ok: true, messageId: info.messageId };
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error("[email] sendMail failed:", message);
    return { ok: false, error: message };
  }
}
