import { logger } from "../logger/index.mjs";
import { ErrorHandler } from "../utils/errors/ErrorHandler.mjs";

//#region src/controllers/eventListener.controller.ts
let clients = [];
const MAX_SSE_CONNECTIONS = 10;
const sendDictionaryUpdate = (args) => {
	const projectIds = args.flatMap((arg) => arg.dictionary.projectIds);
	const filteredClients = clients.filter((client) => projectIds.map((id) => String(id)).includes(String(client.projectId)));
	const data = args.map((arg) => ({
		object: "DICTIONARY",
		status: arg.status,
		data: arg.dictionary
	}));
	process.nextTick(() => {
		for (const client of filteredClients) client.res.raw.write(`data: ${JSON.stringify(data)}\n\n`);
	});
};
/**
* SSE to check the email verification status
*/
const listenChangeSSE = async (request, reply) => {
	const { project } = request.locals || {};
	if (clients.length >= MAX_SSE_CONNECTIONS) return ErrorHandler.handleGenericErrorResponse(reply, "TOO_MANY_CONNECTIONS");
	reply.raw.setHeader("Content-Type", "text/event-stream;charset=utf-8");
	reply.raw.setHeader("Cache-Control", "no-cache, no-transform");
	reply.raw.setHeader("Connection", "keep-alive");
	reply.raw.setHeader("X-Accel-Buffering", "no");
	reply.raw.write(":\n\n");
	reply.raw.flushHeaders?.();
	const clientId = Date.now();
	const newClient = {
		id: clientId,
		projectId: String(project?.id),
		res: { raw: reply.raw }
	};
	clients.push(newClient);
	logger.info(`New client connected to SSE. Total clients: ${clients.length ?? 0}`);
	request.raw.on("close", () => {
		clients = clients.filter((client) => client.id !== clientId);
	});
};

//#endregion
export { listenChangeSSE, sendDictionaryUpdate };
//# sourceMappingURL=eventListener.controller.mjs.map