type Controller = ReadableStreamDefaultController;

const userClients = new Map<string, Set<Controller>>();

/**
 * Thêm connection cho user
 */
export function addClient(userId: string, controller: Controller) {
  if (!userClients.has(userId)) {
    userClients.set(userId, new Set());
  }

  userClients.get(userId)!.add(controller);
}

/**
 * Xoá connection khi tab đóng
 */
export function removeClient(userId: string, controller: Controller) {
  const controllers = userClients.get(userId);
  if (!controllers) return;

  controllers.delete(controller);

  // nếu user không còn tab nào mở thì xoá luôn
  if (controllers.size === 0) {
    userClients.delete(userId);
  }
}

/**
 * Gửi notification cho 1 user
 */
export function sendToUser(userId: string, data: any) {
  const controllers = userClients.get(userId);
  if (!controllers) return;

  for (const controller of controllers) {
    controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
  }
}

/**
 * Gửi cho tất cả user
 */
export function broadcast(data: any) {
  for (const controllers of userClients.values()) {
    for (const controller of controllers) {
      controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
    }
  }
}
