import type { ChatConversationSummary } from '../../mainChatPanel/types';

export const CHAT_CONVERSATIONS_UPDATED_EVENT = 'work-server.chat-conversations-updated';
export const CHAT_CONVERSATION_CLEARED_EVENT = 'work-server.chat-conversation-cleared';

type ChatConversationsUpdatedDetail = {
  items: ChatConversationSummary[];
};

type ChatConversationClearedDetail = {
  item: ChatConversationSummary;
};

export function emitChatConversationsUpdated(items: ChatConversationSummary[]) {
  if (typeof window === 'undefined') {
    return;
  }

  window.dispatchEvent(
    new CustomEvent<ChatConversationsUpdatedDetail>(CHAT_CONVERSATIONS_UPDATED_EVENT, {
      detail: { items },
    }),
  );
}

export function readChatConversationsUpdatedEvent(
  event: Event,
): ChatConversationsUpdatedDetail | null {
  if (!(event instanceof CustomEvent)) {
    return null;
  }

  const detail = event.detail;
  if (!detail || typeof detail !== 'object' || !Array.isArray((detail as { items?: unknown[] }).items)) {
    return null;
  }

  return detail as ChatConversationsUpdatedDetail;
}

export function emitChatConversationCleared(item: ChatConversationSummary) {
  if (typeof window === 'undefined') {
    return;
  }

  window.dispatchEvent(
    new CustomEvent<ChatConversationClearedDetail>(CHAT_CONVERSATION_CLEARED_EVENT, {
      detail: { item },
    }),
  );
}

export function readChatConversationClearedEvent(
  event: Event,
): ChatConversationClearedDetail | null {
  if (!(event instanceof CustomEvent)) {
    return null;
  }

  const detail = event.detail;
  if (!detail || typeof detail !== 'object' || !('item' in (detail as Record<string, unknown>))) {
    return null;
  }

  return detail as ChatConversationClearedDetail;
}
