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.write(`data: ${JSON.stringify(data)}\n\n`);
			client.res.flush?.();
		}
	});
};
/**
* SSE to check the email verification status
*/
const listenChangeSSE = async (req, res) => {
	const { project } = res.locals;
	if (clients.length >= MAX_SSE_CONNECTIONS) {
		ErrorHandler.handleGenericErrorResponse(res, "TOO_MANY_CONNECTIONS");
		return;
	}
	res.setHeader("Content-Type", "text/event-stream;charset=utf-8");
	res.setHeader("Cache-Control", "no-cache, no-transform");
	res.setHeader("Connection", "keep-alive");
	res.setHeader("X-Accel-Buffering", "no");
	res.write(":\n\n");
	res.flushHeaders?.();
	const clientId = Date.now();
	const newClient = {
		id: clientId,
		projectId: String(project.id),
		res
	};
	clients.push(newClient);
	logger.info(`New client connected to SSE. Total clients: ${clients.length ?? 0}`);
	req.on("close", () => {
		clients = clients.filter((client) => client.id !== clientId);
	});
};

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