import { n as readSyncState, r as updateSlugSyncState } from "./sync-state-DMZgzpez.js";
import { n as appendInteraction } from "./interactions-writer-B8XAzdqR.js";
import { n as readSubscriptions, s as writeSubscriptions } from "./push-manager-C0ECQgva.js";
//#region src/sync/gmail-webhook-handler.ts
function decodeGmailPubSubPayload(body) {
	try {
		const data = body?.message?.data;
		if (!data) return null;
		const decoded = Buffer.from(data, "base64").toString("utf-8");
		const parsed = JSON.parse(decoded);
		if (!parsed.emailAddress || !parsed.historyId) return null;
		return {
			emailAddress: parsed.emailAddress,
			historyId: parsed.historyId
		};
	} catch {
		return null;
	}
}
function verifyGmailPubSubSignature(authHeader, expectedToken) {
	if (!authHeader) return false;
	return (authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader) === expectedToken;
}
function findSubscriptionByEmail(subs, emailAddress) {
	return subs.find((s) => s.provider === "gmail" && s.status === "active" && (s.providerData.gmailEmailAddress === emailAddress || s.slug === emailAddress)) ?? null;
}
async function handleGmailPushEvent(dataDir, payload, subscriptionId, options = {}) {
	const subs = await readSubscriptions(dataDir);
	const sub = findSubscriptionByEmail(subs, payload.emailAddress);
	if (!sub) return {
		processed: 0,
		slug: null
	};
	const slug = sub.slug;
	const lastHistoryId = readSyncState(dataDir)[slug]?.lastGmailPushHistoryId ?? sub.providerData.gmailHistoryId ?? "0";
	if (BigInt(payload.historyId) <= BigInt(lastHistoryId)) return {
		processed: 0,
		slug
	};
	const startHistoryId = sub.providerData.gmailHistoryId ?? lastHistoryId;
	const { fetchHistoryFn, fetchMessageFn, appendInteractionFn = appendInteraction, accessToken = "" } = options;
	if (!fetchHistoryFn) return {
		processed: 0,
		slug
	};
	const messages = await fetchHistoryFn(accessToken, startHistoryId);
	let processed = 0;
	for (const msg of messages) {
		if (!fetchMessageFn) continue;
		try {
			const full = await fetchMessageFn(accessToken, msg.id);
			const sourceRef = `gmail://thread/${full.threadId}`;
			await appendInteractionFn(dataDir, slug, {
				date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
				type: "Email",
				direction: "inbound",
				with: full.from,
				subject: full.subject,
				summary: full.body.slice(0, 300) || "(no body)",
				nextSteps: [],
				sourceRef,
				synced: (/* @__PURE__ */ new Date()).toISOString()
			});
			processed++;
		} catch {}
	}
	updateSlugSyncState(dataDir, slug, { lastGmailPushHistoryId: payload.historyId });
	const subIdx = subs.findIndex((s) => s.id === sub.id);
	if (subIdx !== -1) {
		subs[subIdx] = {
			...subs[subIdx],
			eventsProcessed: subs[subIdx].eventsProcessed + 1,
			lastEventAt: (/* @__PURE__ */ new Date()).toISOString()
		};
		await writeSubscriptions(dataDir, subs);
	}
	return {
		processed,
		slug
	};
}
function buildGmailRenewFn(accessToken, topicName, registerFn) {
	return async (_sub) => {
		const registration = await (registerFn ?? (async (token, topic) => {
			const { registerGmailWatch } = await import("./gmail-push-watch-DELQFMPk.js");
			return registerGmailWatch(token, topic);
		}))(accessToken, topicName);
		return {
			expiresAt: new Date(Number(registration.expiration)).toISOString(),
			providerData: { gmailHistoryId: registration.historyId }
		};
	};
}
//#endregion
export { verifyGmailPubSubSignature as i, decodeGmailPubSubPayload as n, handleGmailPushEvent as r, buildGmailRenewFn as t };

//# sourceMappingURL=gmail-webhook-handler-BzOFbvgh.js.map