const TRANSIENT_CONVERSATION_TITLES = new Set([
  '새 대화',
  '대화 내용을 불러오는 중입니다.',
  '첫 요청을 보내면 대화가 저장됩니다.',
  '새 채팅방을 준비하는 중입니다.',
  '삭제되었거나 만료된 채팅방입니다.',
]);

function normalizeConversationTitle(value: string | null | undefined) {
  return String(value ?? '').trim();
}

function isTransientConversationTitle(value: string) {
  return TRANSIENT_CONVERSATION_TITLES.has(value);
}

export function resolveMergedConversationTitle(
  previousTitle: string | null | undefined,
  nextTitle: string | null | undefined,
  options?: { preservePrevious?: boolean },
) {
  const normalizedPreviousTitle = normalizeConversationTitle(previousTitle);
  const normalizedNextTitle = normalizeConversationTitle(nextTitle);

  if (options?.preservePrevious) {
    return normalizedPreviousTitle || normalizedNextTitle;
  }

  if (!normalizedNextTitle) {
    return normalizedPreviousTitle;
  }

  if (!normalizedPreviousTitle) {
    return normalizedNextTitle;
  }

  if (
    isTransientConversationTitle(normalizedNextTitle) &&
    !isTransientConversationTitle(normalizedPreviousTitle)
  ) {
    return normalizedPreviousTitle;
  }

  return normalizedNextTitle;
}
