export type WenfanHistoryMessage = {
  role: string;
  content?: string;
};

export type WenfanConversationRecord<TMessage extends WenfanHistoryMessage> = {
  id: string;
  title: string;
  messages: TMessage[];
};

const DEFAULT_CONVERSATION_TITLE = '新对话';

function getConversationTitle<TMessage extends WenfanHistoryMessage>(messages: TMessage[]): string {
  const firstQuestion = messages.find((message) => message.role === 'user' && message.content?.trim());
  return firstQuestion?.content?.trim() || DEFAULT_CONVERSATION_TITLE;
}

export function createWenfanConversationRecord<TMessage extends WenfanHistoryMessage>(
  id: string,
  messages: TMessage[],
): WenfanConversationRecord<TMessage> {
  return {
    id,
    title: getConversationTitle(messages),
    messages,
  };
}

export function updateWenfanConversationRecord<TMessage extends WenfanHistoryMessage>(
  records: WenfanConversationRecord<TMessage>[],
  activeId: string | null | undefined,
  messages: TMessage[],
): WenfanConversationRecord<TMessage>[] {
  if (!activeId) return records;

  return records.map((record) =>
    record.id === activeId
      ? {
          ...record,
          title: getConversationTitle(messages),
          messages,
        }
      : record,
  );
}

export function deleteWenfanConversationRecord<TMessage extends WenfanHistoryMessage>(
  records: WenfanConversationRecord<TMessage>[],
  id: string,
): WenfanConversationRecord<TMessage>[] {
  return records.filter((record) => record.id !== id);
}
