const KEEPALIVE_MS = 15_000;

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

function encodeSseChunk(value: string) {
  return new TextEncoder().encode(value);
}

export async function GET(request: Request) {
  const abortSignal = request.signal;

  const stream = new ReadableStream<Uint8Array>({
    start(controller) {
      let closed = false;
      let keepaliveHandle: ReturnType<typeof setInterval> | null = null;

      const closeStream = () => {
        if (closed) {
          return;
        }
        closed = true;
        if (keepaliveHandle !== null) {
          clearInterval(keepaliveHandle);
          keepaliveHandle = null;
        }
        controller.close();
      };

      abortSignal.addEventListener("abort", closeStream, { once: true });
      controller.enqueue(encodeSseChunk(": stream-open\n\n"));
      controller.enqueue(encodeSseChunk("event: upstream-open\ndata: {}\n\n"));

      keepaliveHandle = setInterval(() => {
        if (!closed) {
          controller.enqueue(encodeSseChunk(`: keepalive ${Date.now()}\n\n`));
        }
      }, KEEPALIVE_MS);
    },
  });

  return new Response(stream, {
    headers: {
      "cache-control": "no-cache, no-transform",
      "content-type": "text/event-stream; charset=utf-8",
      connection: "keep-alive",
      "x-accel-buffering": "no",
    },
  });
}
