type Client = {
  userId: string;
  write: (payload: any) => void;
  res: any;
};

const clientsByUser: Map<string, Set<Client>> = new Map();

export function addSseClient(userId: string, res: any): () => void {
  const client: Client = {
    userId,
    res,
    write: (payload: any) => {
      try {
        res.write(`data: ${JSON.stringify(payload)}\n\n`);
      } catch {}
    },
  };

  if (!clientsByUser.has(userId)) clientsByUser.set(userId, new Set());
  clientsByUser.get(userId)!.add(client);

  // Initial hello
  client.write({ type: 'hello', at: Date.now() });

  // Heartbeat to keep connections alive through proxies
  const heartbeat = setInterval(() => {
    try { res.write(`: ping\n\n`); } catch {}
  }, 25000);

  // Return cleanup
  return () => {
    clearInterval(heartbeat);
    try { res.end(); } catch {}
    clientsByUser.get(userId)?.delete(client);
    if (clientsByUser.get(userId)?.size === 0) clientsByUser.delete(userId);
  };
}

export function sendEvent(userId: string, event: any): void {
  const set = clientsByUser.get(userId);
  if (!set || set.size === 0) return;
  for (const client of set) client.write(event);
}

export function sendToBoth(userA: string, userB: string, event: any): void {
  sendEvent(userA, event);
  if (userB !== userA) sendEvent(userB, event);
}


