import { notificationEmitter } from "@/lib/notifications";
import type { Notification } from "@/lib/notifications";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const stream = new ReadableStream({
    start(controller) {
      function onNotification(notification: Notification) {
        controller.enqueue(`data: ${JSON.stringify(notification)}\n\n`);
      }

      notificationEmitter.on("notification", onNotification);

      // Keepalive every 15 seconds
      const keepalive = setInterval(() => {
        try {
          controller.enqueue(": keepalive\n\n");
        } catch {
          clearInterval(keepalive);
        }
      }, 15_000);

      // Cleanup on disconnect
      request.signal.addEventListener("abort", () => {
        notificationEmitter.off("notification", onNotification);
        clearInterval(keepalive);
        try {
          controller.close();
        } catch {
          // already closed
        }
      });
    },
  });

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
      "X-Accel-Buffering": "no",
    },
  });
}
