import type { EmailPayload } from "./types";

const BREVO_ENDPOINT = "https://api.brevo.com/v3/smtp/email";

/**
 * Send a single transactional email via Brevo REST API.
 */
export async function sendEmail(payload: EmailPayload): Promise<void> {
  const apiKey = process.env.BREVO_API_KEY;
  if (!apiKey) {
    throw new Error("BREVO_API_KEY must be set for email notifications");
  }

  const fromEmail =
    process.env.NOTIFICATION_FROM_EMAIL ?? "noreply@beletage.ro";
  const fromName = process.env.NOTIFICATION_FROM_NAME ?? "ArchiTools";

  const recipients = payload.to
    .split(",")
    .map((addr) => addr.trim())
    .filter(Boolean)
    .map((email) => ({ email }));

  if (recipients.length === 0) {
    throw new Error("sendEmail: no recipients");
  }

  const res = await fetch(BREVO_ENDPOINT, {
    method: "POST",
    headers: {
      accept: "application/json",
      "content-type": "application/json",
      "api-key": apiKey,
    },
    body: JSON.stringify({
      sender: { name: fromName, email: fromEmail },
      to: recipients,
      subject: payload.subject,
      htmlContent: payload.html,
    }),
  });

  if (!res.ok) {
    const detail = await res.text().catch(() => "");
    throw new Error(`Brevo API ${res.status}: ${detail.slice(0, 300)}`);
  }
}
