import { getSession } from '@server/auth';
import { subscribeEscalations } from '@server/utils/escalationBus';
import { wrapRouteHandler } from '@server/logger/request';

export const dynamic = 'force-dynamic';

async function handleGET() {
  const session = await getSession();
  if (!session || !session.restaurantId) {
    return new Response('Unauthorized', { status: 401 });
  }

  const restaurantId = session.restaurantId;

  let unsubscribe: (() => void) | undefined;

  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode(': connected\n\n'));
      unsubscribe = subscribeEscalations(restaurantId, controller);
    },
    cancel() {
      unsubscribe?.();
    },
  });

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

export const GET = wrapRouteHandler(handleGET);
