import { MailProviderError } from "./index.js";
import { Resend } from "resend";
//#region src/resend.ts
function toList(value) {
	return Array.isArray(value) ? value : [value];
}
function toResendPayload(msg) {
	const base = {
		from: msg.from,
		to: toList(msg.to),
		cc: msg.cc ? toList(msg.cc) : void 0,
		bcc: msg.bcc ? toList(msg.bcc) : void 0,
		subject: msg.subject,
		headers: msg.headers,
		replyTo: msg.replyTo,
		tags: msg.tags ? Object.entries(msg.tags).map(([name, value]) => ({
			name,
			value
		})) : void 0
	};
	if (msg.html) return {
		...base,
		html: msg.html,
		text: msg.text
	};
	return {
		...base,
		text: msg.text
	};
}
function makeResendAdapter({ apiKey }) {
	const resend = new Resend(apiKey);
	return { async send(msg) {
		try {
			const { data, error } = await resend.emails.send(toResendPayload(msg), msg.idempotencyKey ? { idempotencyKey: msg.idempotencyKey } : void 0);
			if (error) throw new MailProviderError(error.message, "resend", error.statusCode != null && error.statusCode >= 500, error);
			if (!data?.id) throw new MailProviderError("resend returned no message id", "resend", false);
			return {
				id: data.id,
				provider: "resend"
			};
		} catch (err) {
			if (err instanceof MailProviderError) throw err;
			throw new MailProviderError(err instanceof Error ? err.message : "resend send failed", "resend", false, err);
		}
	} };
}
//#endregion
export { makeResendAdapter };
