import { MailProviderError } from "./index.js";
import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
//#region src/ses.ts
function toList(value) {
	if (value === void 0) return void 0;
	return Array.isArray(value) ? value : [value];
}
function toCommandInput(msg) {
	const body = {
		Subject: {
			Data: msg.subject,
			Charset: "UTF-8"
		},
		Body: {}
	};
	if (msg.html) body.Body.Html = {
		Data: msg.html,
		Charset: "UTF-8"
	};
	if (msg.text) body.Body.Text = {
		Data: msg.text,
		Charset: "UTF-8"
	};
	return {
		FromEmailAddress: msg.from,
		Destination: {
			ToAddresses: toList(msg.to),
			CcAddresses: toList(msg.cc),
			BccAddresses: toList(msg.bcc)
		},
		ReplyToAddresses: msg.replyTo ? [msg.replyTo] : void 0,
		Content: { Simple: body },
		EmailTags: msg.tags ? Object.entries(msg.tags).map(([Name, Value]) => ({
			Name,
			Value
		})) : void 0
	};
}
function makeSesAdapter({ region, credentials, client }) {
	const ses = client ?? new SESv2Client({
		region,
		credentials
	});
	return { async send(msg) {
		try {
			const response = await ses.send(new SendEmailCommand(toCommandInput(msg)));
			if (!response.MessageId) throw new MailProviderError("ses returned no message id", "ses", false, response);
			return {
				id: response.MessageId,
				provider: "ses"
			};
		} catch (err) {
			if (err instanceof MailProviderError) throw err;
			const statusCode = typeof err === "object" && err !== null && "$metadata" in err && typeof err.$metadata === "object" && err.$metadata !== null && "httpStatusCode" in err.$metadata && typeof err.$metadata.httpStatusCode === "number" ? err.$metadata.httpStatusCode : void 0;
			throw new MailProviderError(err instanceof Error ? err.message : "ses send failed", "ses", statusCode !== void 0 && statusCode >= 500, err);
		}
	} };
}
//#endregion
export { makeSesAdapter };
