import { getStatus } from "./outlookIntegrationClient.mjs";
//#region src/integrations/outlook/outlookIntegrationStatus.ts
const DEFAULT_STATUS = {
	connected: false,
	mailboxPrincipal: null,
	expiresAt: null,
	scope: null,
	loaded: false,
	error: null
};
let cachedStatus = { ...DEFAULT_STATUS };
const listeners = /* @__PURE__ */ new Set();
let inFlight = null;
let hasFetchedOnce = false;
let statusVersion = 0;
function getOutlookStatus() {
	return cachedStatus;
}
function isOutlookConnected() {
	return !!cachedStatus.connected;
}
function setOutlookDisconnected() {
	cachedStatus = {
		...cachedStatus,
		connected: false,
		mailboxPrincipal: null,
		expiresAt: null,
		scope: null,
		loaded: true,
		error: null
	};
	publish();
}
function resetOutlookStatus() {
	statusVersion += 1;
	hasFetchedOnce = false;
	inFlight = null;
	cachedStatus = { ...DEFAULT_STATUS };
	publish();
}
function subscribeOutlookStatus(handler) {
	listeners.add(handler);
	try {
		handler(cachedStatus);
	} catch (err) {
		console.warn("OutlookStatus: failed to publish initial status", err);
	}
	return () => {
		listeners.delete(handler);
	};
}
async function refreshOutlookStatus() {
	if (inFlight !== null) return inFlight;
	const requestVersion = statusVersion;
	const request = getStatus().then((status) => {
		if (requestVersion !== statusVersion) return cachedStatus;
		cachedStatus = mapStatus(status);
		hasFetchedOnce = true;
		publish();
		return cachedStatus;
	}).catch((err) => {
		if (requestVersion !== statusVersion) return cachedStatus;
		const message = err instanceof Error ? err.message : "Unable to load Outlook integration status.";
		cachedStatus = {
			...cachedStatus,
			loaded: true,
			error: message
		};
		publish();
		throw err;
	}).finally(() => {
		if (inFlight === request) inFlight = null;
	});
	inFlight = request;
	return request;
}
function ensureOutlookStatusLoaded() {
	return hasFetchedOnce ? Promise.resolve(cachedStatus) : refreshOutlookStatus();
}
function mapStatus(status) {
	return {
		connected: !!status?.connected,
		mailboxPrincipal: status?.mailboxPrincipal ?? null,
		expiresAt: status?.expiresAt ?? null,
		scope: status?.scope ?? null,
		loaded: true,
		error: null
	};
}
function publish() {
	listeners.forEach((handler) => {
		try {
			handler(cachedStatus);
		} catch (err) {
			console.warn("OutlookStatus: subscriber threw an error", err);
		}
	});
}
//#endregion
export { ensureOutlookStatusLoaded, getOutlookStatus, isOutlookConnected, refreshOutlookStatus, resetOutlookStatus, setOutlookDisconnected, subscribeOutlookStatus };

//# sourceMappingURL=outlookIntegrationStatus.mjs.map