import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
//#region src/gateway/service/sse-hub.ts
init_logger();
const log = createLogger("GatewayService");
const EVENT_BUFFER_SIZE = 200;
var GatewaySseHub = class {
	eventCounter = 0;
	subscribers = /* @__PURE__ */ new Map();
	eventBuffers = /* @__PURE__ */ new Map();
	subscribe(sessionId, listener) {
		this.subscribers.set(sessionId, listener);
		if (!this.eventBuffers.has(sessionId)) this.eventBuffers.set(sessionId, []);
		log.debug({ sessionId }, "Event subscriber added");
		return () => {
			this.subscribers.delete(sessionId);
			setTimeout(() => {
				if (!this.subscribers.has(sessionId)) this.eventBuffers.delete(sessionId);
			}, 5 * 6e4);
			log.debug({ sessionId }, "Event subscriber removed");
		};
	}
	emit(type, payload) {
		const event = {
			id: String(++this.eventCounter),
			type,
			payload
		};
		for (const [sessionId, listener] of this.subscribers) {
			const buf = this.eventBuffers.get(sessionId) || [];
			buf.push(event);
			if (buf.length > EVENT_BUFFER_SIZE) buf.shift();
			this.eventBuffers.set(sessionId, buf);
			try {
				listener(event);
			} catch (err) {
				log.warn({
					sessionId,
					err
				}, "Failed to deliver event to subscriber");
			}
		}
	}
	getEventsSince(sessionId, lastEventId) {
		const buf = this.eventBuffers.get(sessionId);
		if (!buf) return [];
		const idx = buf.findIndex((e) => e.id === lastEventId);
		if (idx === -1) return buf;
		return buf.slice(idx + 1);
	}
};
//#endregion
export { GatewaySseHub };

//# sourceMappingURL=sse-hub.js.map