import { MailProviderError } from "./index.js";
//#region src/brevo.ts
const BREVO_URL = "https://api.brevo.com/v3/smtp/email";
function toRecipients(value) {
	return (Array.isArray(value) ? value : [value]).map((email) => ({ email }));
}
function parseFrom(from) {
	const angle = from.match(/^(.+?)\s*<([^>]+)>$/);
	if (angle) return {
		name: angle[1].trim(),
		email: angle[2].trim()
	};
	return { email: from.trim() };
}
function makeBrevoAdapter({ apiKey, fetchImpl = fetch }) {
	return { async send(msg) {
		const body = {
			sender: parseFrom(msg.from),
			to: toRecipients(msg.to),
			cc: msg.cc ? toRecipients(msg.cc) : void 0,
			bcc: msg.bcc ? toRecipients(msg.bcc) : void 0,
			replyTo: msg.replyTo ? { email: msg.replyTo } : void 0,
			subject: msg.subject,
			htmlContent: msg.html,
			textContent: msg.text,
			headers: msg.headers
		};
		let response;
		try {
			response = await fetchImpl(BREVO_URL, {
				method: "POST",
				headers: {
					"api-key": apiKey,
					"content-type": "application/json",
					accept: "application/json",
					...msg.idempotencyKey ? { "Idempotency-Key": msg.idempotencyKey } : {}
				},
				body: JSON.stringify(body)
			});
		} catch (err) {
			throw new MailProviderError(err instanceof Error ? err.message : "brevo fetch failed", "brevo", true, err);
		}
		const payload = await response.json().catch(() => null);
		if (!response.ok) throw new MailProviderError(payload?.message ?? `brevo request failed (${response.status})`, "brevo", response.status >= 500, payload);
		if (!payload?.messageId) throw new MailProviderError("brevo returned no message id", "brevo", false, payload);
		return {
			id: payload.messageId,
			provider: "brevo"
		};
	} };
}
//#endregion
export { makeBrevoAdapter };
