import { i as writeJsonFile } from "./json-store-WWsFzXub.js";
import path from "path";
import fs from "fs";
//#region src/sync/push-manager.ts
function makePushSubId() {
	return `psub_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`;
}
function subscriptionsPath(dataDir) {
	return path.join(dataDir, ".agentic", "push-subscriptions.json");
}
async function readSubscriptions(dataDir) {
	const filePath = subscriptionsPath(dataDir);
	if (!fs.existsSync(filePath)) return [];
	try {
		const raw = fs.readFileSync(filePath, "utf-8");
		return JSON.parse(raw).subscriptions ?? [];
	} catch {
		return [];
	}
}
async function writeSubscriptions(dataDir, subs) {
	const filePath = subscriptionsPath(dataDir);
	fs.mkdirSync(path.dirname(filePath), { recursive: true });
	writeJsonFile(filePath, {
		subscriptions: subs,
		updatedAt: (/* @__PURE__ */ new Date()).toISOString()
	});
}
function expiresAtForProvider(provider) {
	if (provider === "gmail") return new Date(Date.now() + 10080 * 60 * 1e3).toISOString();
	if (provider === "microsoft-graph") return new Date(Date.now() + 4320 * 60 * 1e3).toISOString();
	return null;
}
async function register(dataDir, provider, slug, opts) {
	const subs = await readSubscriptions(dataDir);
	const sub = {
		id: makePushSubId(),
		provider,
		slug,
		webhookUrl: opts.webhookUrl,
		expiresAt: expiresAtForProvider(provider),
		renewedAt: null,
		createdAt: (/* @__PURE__ */ new Date()).toISOString(),
		providerData: opts.providerData ?? {},
		status: "active",
		lastEventAt: null,
		eventsProcessed: 0
	};
	await writeSubscriptions(dataDir, [...subs, sub]);
	return sub;
}
async function revoke(dataDir, id) {
	const subs = await readSubscriptions(dataDir);
	const idx = subs.findIndex((s) => s.id === id);
	if (idx === -1) throw new Error(`Subscription ${id} not found`);
	subs[idx] = {
		...subs[idx],
		status: "revoked"
	};
	await writeSubscriptions(dataDir, subs);
}
async function renewExpiringSubscriptions(dataDir, renewFn, thresholdHours = 24) {
	const subs = await readSubscriptions(dataDir);
	const thresholdMs = thresholdHours * 60 * 60 * 1e3;
	const cutoff = Date.now() + thresholdMs;
	const renewed = [];
	const errors = [];
	const PERMANENT_FAILURE_THRESHOLD = 3;
	for (let i = 0; i < subs.length; i++) {
		const sub = subs[i];
		if (sub.status !== "active" && sub.status !== "error") continue;
		if (sub.expiresAt === null) continue;
		if (new Date(sub.expiresAt).getTime() > cutoff) continue;
		try {
			const result = await renewFn(sub);
			subs[i] = {
				...sub,
				status: "active",
				expiresAt: result.expiresAt,
				renewedAt: (/* @__PURE__ */ new Date()).toISOString(),
				renewFailures: 0,
				providerData: result.providerData ? {
					...sub.providerData,
					...result.providerData
				} : sub.providerData
			};
			renewed.push(sub.id);
		} catch {
			const failures = (sub.renewFailures ?? 0) + 1;
			const newStatus = failures >= PERMANENT_FAILURE_THRESHOLD ? "permanently_failed" : "error";
			subs[i] = {
				...sub,
				status: newStatus,
				renewFailures: failures
			};
			errors.push(sub.id);
		}
	}
	await writeSubscriptions(dataDir, subs);
	return {
		renewed,
		errors
	};
}
//#endregion
export { revoke as a, renewExpiringSubscriptions as i, readSubscriptions as n, subscriptionsPath as o, register as r, writeSubscriptions as s, makePushSubId as t };

//# sourceMappingURL=push-manager-C0ECQgva.js.map