type EscalationEvent = {
  restaurantId: string;
  conversationId: string;
  reason: string;
  customerName?: string;
};

type Subscriber = {
  restaurantId: string;
  controller: ReadableStreamDefaultController;
};

const subscribers: Set<Subscriber> = new Set();

const HEARTBEAT_INTERVAL_MS = 25_000;

function startHeartbeat(): ReturnType<typeof setInterval> {
  const ping = new TextEncoder().encode(': ping\n\n');
  return setInterval(() => {
    for (const sub of subscribers) {
      try {
        sub.controller.enqueue(ping);
      } catch {
        subscribers.delete(sub);
      }
    }
  }, HEARTBEAT_INTERVAL_MS);
}

let heartbeatTimer: ReturnType<typeof setInterval> | null = null;

export function subscribeEscalations(restaurantId: string, controller: ReadableStreamDefaultController): () => void {
  if (!heartbeatTimer) {
    heartbeatTimer = startHeartbeat();
  }
  const sub: Subscriber = { restaurantId, controller };
  subscribers.add(sub);
  return () => {
    subscribers.delete(sub);
    if (subscribers.size === 0 && heartbeatTimer) {
      clearInterval(heartbeatTimer);
      heartbeatTimer = null;
    }
  };
}

export function broadcastEscalation(event: EscalationEvent): void {
  const payload = `data: ${JSON.stringify(event)}\n\n`;
  const encoded = new TextEncoder().encode(payload);
  for (const sub of subscribers) {
    if (sub.restaurantId === event.restaurantId) {
      try {
        sub.controller.enqueue(encoded);
      } catch {
        subscribers.delete(sub);
      }
    }
  }
}
