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

export const dynamic = 'force-dynamic';

export async function GET() {
  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',
    },
  });
}
