import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
import type { EventBus } from "../services/eventbus";

export function eventRoutes(bus: EventBus): Hono {
	const router = new Hono();

	router.get("/events", (c) => {
		return streamSSE(c, async (stream) => {
			let id = 0;
			const unsubscribe = bus.subscribe(async (event) => {
				await stream.writeSSE({
					data: JSON.stringify(event),
					event: event.type as string,
					id: String(id++),
				});
			});

			stream.onAbort(() => {
				unsubscribe();
			});

			// keep connection alive
			while (true) {
				await stream.sleep(30000);
			}
		});
	});

	return router;
}
