type SharedActiveConversationSnapshot = {
  sessionId: string;
  title: string;
};

const sharedActiveConversation = {
  sessionId: '',
  title: '',
  subscribers: new Set<() => void>(),
};

function emitSharedActiveConversation() {
  sharedActiveConversation.subscribers.forEach((listener) => {
    listener();
  });
}

export function getSharedActiveConversationSnapshot(): SharedActiveConversationSnapshot {
  return {
    sessionId: sharedActiveConversation.sessionId,
    title: sharedActiveConversation.title,
  };
}

export function subscribeSharedActiveConversation(listener: () => void) {
  sharedActiveConversation.subscribers.add(listener);

  return () => {
    sharedActiveConversation.subscribers.delete(listener);
  };
}

export function setSharedActiveConversationSnapshot(snapshot: SharedActiveConversationSnapshot) {
  const nextSessionId = snapshot.sessionId.trim();
  const nextTitle = snapshot.title.trim();

  if (sharedActiveConversation.sessionId === nextSessionId && sharedActiveConversation.title === nextTitle) {
    return;
  }

  sharedActiveConversation.sessionId = nextSessionId;
  sharedActiveConversation.title = nextTitle;
  emitSharedActiveConversation();
}
