/**
 * Client d'envoi d'e-mail (fournisseur : Resend, un seul appel HTTP,
 * pas de config SMTP à gérer). Remplacer uniquement sendEmail() pour
 * changer de fournisseur (utile en marque blanche, un SMTP par client).
 *
 * Sans RESEND_API_KEY configurée : l'email est loggé en console au lieu
 * d'être envoyé, pour pouvoir tester tout le parcours sans compte email.
 */

interface EmailAttachment {
  filename: string;
  content: Buffer | Uint8Array;
}

interface SendEmailInput {
  to: string;
  subject: string;
  html: string;
  attachments?: EmailAttachment[];
}

interface SendEmailResult {
  success: boolean;
  simulated: boolean;
  error?: string;
}

export async function sendEmail({
  to,
  subject,
  html,
  attachments,
}: SendEmailInput): Promise<SendEmailResult> {
  const apiKey = process.env.RESEND_API_KEY;
  const from = process.env.EMAIL_FROM ?? "Azelior <onboarding@resend.dev>";

  if (!apiKey) {
    console.log("--- [EMAIL SIMULÉ - pas de RESEND_API_KEY configurée] ---");
    console.log("À :", to);
    console.log("Sujet :", subject);
    console.log("Pièces jointes :", attachments?.map((a) => a.filename).join(", ") || "aucune");
    console.log("----------------------------------------------------------");
    return { success: true, simulated: true };
  }

  try {
    const res = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        from,
        to,
        subject,
        html,
        attachments: attachments?.map((a) => ({
          filename: a.filename,
          content: Buffer.from(a.content).toString("base64"),
        })),
      }),
    });

    if (!res.ok) {
      const errorText = await res.text();
      console.error("[sendEmail] Échec Resend:", res.status, errorText);
      return { success: false, simulated: false, error: errorText };
    }

    return { success: true, simulated: false };
  } catch (err) {
    console.error("[sendEmail] Erreur réseau:", err);
    return {
      success: false,
      simulated: false,
      error: err instanceof Error ? err.message : "Erreur inconnue",
    };
  }
}
