import { a as registerMarketingAdapter, n as MarketingProviderError, s as sendCampaignThroughCompliance } from "./src-BekHnJEo.js";
//#region src/brevo.ts
const BREVO_BASE = "https://api.brevo.com/v3";
function mapBrevoSuppressionReason(code) {
	const c = code?.toLowerCase() ?? "";
	if (c.includes("bounce")) return "bounce";
	if (c.includes("spam") || c.includes("complaint")) return "complaint";
	if (c.includes("unsubscrib")) return "unsubscribe";
	return "manual";
}
async function brevoFetch(creds, path, init) {
	const fetchImpl = creds.fetchImpl ?? fetch;
	try {
		return await fetchImpl(`${BREVO_BASE}${path}`, {
			...init,
			headers: {
				"api-key": creds.apiKey,
				accept: "application/json",
				"content-type": "application/json",
				...init?.headers ?? {}
			}
		});
	} catch (err) {
		throw new MarketingProviderError(err instanceof Error ? err.message : "brevo fetch failed", "brevo", true, err);
	}
}
async function parseBrevoError(response) {
	const body = await response.json().catch(() => null);
	return new MarketingProviderError(body?.message ?? `brevo request failed (${response.status})`, "brevo", response.status >= 500, body);
}
async function createBrevoDoubleOptInContact(creds, contact, opts) {
	const response = await brevoFetch(creds, "/contacts/doubleOptinConfirmation", {
		method: "POST",
		body: JSON.stringify({
			email: contact.email,
			attributes: contact.attributes,
			includeListIds: [opts.listId],
			templateId: opts.templateId,
			redirectionUrl: opts.redirectionUrl
		})
	});
	if (!response.ok) throw await parseBrevoError(response);
}
function makeBrevoAdapter(creds) {
	const campaignRecipients = /* @__PURE__ */ new Map();
	return {
		name: "brevo",
		supports: {
			segments: true,
			scheduling: true,
			automation: true
		},
		async upsertContact(contact, listId, opts) {
			const body = {
				email: contact.email,
				attributes: contact.attributes,
				updateEnabled: opts?.updateEnabled ?? true
			};
			if (listId) body.listIds = [Number.parseInt(listId, 10)];
			const response = await brevoFetch(creds, "/contacts", {
				method: "POST",
				body: JSON.stringify(body)
			});
			if (!response.ok) throw await parseBrevoError(response);
		},
		async removeContact(email) {
			const response = await brevoFetch(creds, `/contacts/${encodeURIComponent(email)}`, { method: "DELETE" });
			if (!response.ok && response.status !== 404) throw await parseBrevoError(response);
		},
		async tagContact(email, tag) {
			const response = await brevoFetch(creds, `/contacts/${encodeURIComponent(email)}`, {
				method: "PUT",
				body: JSON.stringify({ attributes: { TAG: tag } })
			});
			if (!response.ok) throw await parseBrevoError(response);
		},
		async createList(name) {
			const response = await brevoFetch(creds, "/contacts/lists", {
				method: "POST",
				body: JSON.stringify({
					name,
					folderId: 1
				})
			});
			if (!response.ok) throw await parseBrevoError(response);
			const payload = await response.json();
			return {
				id: String(payload.id),
				name
			};
		},
		async lists() {
			const response = await brevoFetch(creds, "/contacts/lists?limit=50", { method: "GET" });
			if (!response.ok) throw await parseBrevoError(response);
			return ((await response.json()).lists ?? []).map((list) => ({
				id: String(list.id),
				name: list.name
			}));
		},
		async createCampaign(campaign) {
			const response = await brevoFetch(creds, "/emailCampaigns", {
				method: "POST",
				body: JSON.stringify({
					name: campaign.name,
					subject: campaign.subject,
					htmlContent: campaign.html,
					textContent: campaign.text,
					recipients: { listIds: campaign.listIds.map((id) => Number.parseInt(id, 10)) },
					sender: {
						email: creds.senderEmail,
						name: creds.senderName
					}
				})
			});
			if (!response.ok) throw await parseBrevoError(response);
			const payload = await response.json();
			const created = {
				...campaign,
				id: String(payload.id)
			};
			campaignRecipients.set(created.id, []);
			return created;
		},
		async sendCampaign(campaignId, opts) {
			if ((campaignRecipients.get(campaignId) ?? []).length === 0) {
				const listResponse = await brevoFetch(creds, `/emailCampaigns/${encodeURIComponent(campaignId)}`, { method: "GET" });
				if (listResponse.ok) {
					const listIds = (await listResponse.json()).recipients?.lists ?? [];
					const collected = [];
					for (const listId of listIds) {
						const contactsResponse = await brevoFetch(creds, `/contacts/lists/${listId}/contacts?limit=50`, { method: "GET" });
						if (!contactsResponse.ok) continue;
						const contactsPayload = await contactsResponse.json();
						for (const contact of contactsPayload.contacts ?? []) collected.push(contact.email);
					}
					campaignRecipients.set(campaignId, collected);
				}
			}
			const resolvedRecipients = campaignRecipients.get(campaignId) ?? [];
			const campaign = {
				id: campaignId,
				name: campaignId,
				subject: "campaign",
				html: "<p>campaign</p>",
				listIds: [],
				region: opts.legal.region
			};
			const complianceResult = await sendCampaignThroughCompliance(creds.complianceStore, {
				campaignId,
				campaign,
				legal: opts.legal,
				recipients: resolvedRecipients,
				trackingBaseUrl: opts.trackingBaseUrl
			}, async () => {});
			if (complianceResult.sent.length === 0) return complianceResult;
			const response = await brevoFetch(creds, `/emailCampaigns/${encodeURIComponent(campaignId)}/sendNow`, { method: "POST" });
			if (!response.ok) throw await parseBrevoError(response);
			return complianceResult;
		},
		async campaignStats(campaignId) {
			const response = await brevoFetch(creds, `/emailCampaigns/${encodeURIComponent(campaignId)}?statistics=globalStats&excludeHtmlContent=true`, { method: "GET" });
			if (!response.ok) throw await parseBrevoError(response);
			const stats = (await response.json()).statistics?.globalStats;
			return {
				opens: stats?.uniqueViews ?? 0,
				clicks: stats?.uniqueClicks ?? 0,
				bounces: stats?.hardBounces ?? 0,
				unsubs: stats?.unsubscriptions ?? 0
			};
		},
		async syncSuppression() {
			const response = await brevoFetch(creds, "/smtp/blockedContacts?limit=50", { method: "GET" });
			if (!response.ok) throw await parseBrevoError(response);
			return ((await response.json()).contacts ?? []).map((entry) => ({
				email: entry.email,
				reason: mapBrevoSuppressionReason(entry.reason?.code),
				suppressedAt: entry.blockedAt ?? ""
			}));
		},
		async createSegment(def) {
			const response = await brevoFetch(creds, "/contacts/segments", {
				method: "POST",
				body: JSON.stringify({
					segmentName: def.name,
					listIds: [def.listId]
				})
			});
			if (!response.ok) throw await parseBrevoError(response);
			return {
				id: (await response.json()).id,
				name: def.name
			};
		},
		async scheduleCampaign(campaignId, scheduledAt) {
			const response = await brevoFetch(creds, `/emailCampaigns/${typeof campaignId === "string" ? campaignId : String(campaignId)}`, {
				method: "PUT",
				body: JSON.stringify({ scheduledAt })
			});
			if (!response.ok) throw await parseBrevoError(response);
		},
		async createAutomation(def) {
			const listId = typeof def.listId === "string" ? Number.parseInt(def.listId, 10) : def.listId;
			const response = await brevoFetch(creds, "/automations", {
				method: "POST",
				body: JSON.stringify({
					name: def.name,
					listIds: [listId]
				})
			});
			if (!response.ok) throw await parseBrevoError(response);
			return {
				id: (await response.json()).id,
				name: def.name
			};
		}
	};
}
registerMarketingAdapter("brevo", (creds) => makeBrevoAdapter(creds));
//#endregion
export { createBrevoDoubleOptInContact, makeBrevoAdapter };
