import test from 'node:test';
import assert from 'node:assert/strict';
import { mergeConversationItemsPreservingRequestedSession } from './conversationListMerge.js';
import { resolveMergedConversationTitle } from '../../mainChatPanel/conversationTitle.js';

function createConversationSummary(overrides) {
  return {
    sessionId: overrides.sessionId,
    clientId: overrides.clientId ?? null,
    isDraftOnly: overrides.isDraftOnly,
    draftText: overrides.draftText ?? '',
    title: overrides.title,
    requestBadgeLabel: overrides.requestBadgeLabel ?? null,
    codexModel: overrides.codexModel ?? null,
    chatTypeId: overrides.chatTypeId ?? null,
    lastChatTypeId: overrides.lastChatTypeId ?? null,
    generalSectionName: overrides.generalSectionName ?? null,
    contextLabel: overrides.contextLabel ?? null,
    contextDescription: overrides.contextDescription ?? null,
    roomScope: overrides.roomScope ?? null,
    notifyOffline: overrides.notifyOffline ?? true,
    hasUnreadResponse: overrides.hasUnreadResponse ?? false,
    currentRequestId: overrides.currentRequestId ?? null,
    currentJobStatus: overrides.currentJobStatus ?? null,
    currentJobMessage: overrides.currentJobMessage ?? null,
    currentQueueSize: overrides.currentQueueSize ?? 0,
    currentStatusUpdatedAt: overrides.currentStatusUpdatedAt ?? null,
    isPendingWork: overrides.isPendingWork ?? false,
    pendingWorkReason: overrides.pendingWorkReason ?? null,
    lastRequestPreview: overrides.lastRequestPreview ?? '',
    lastMessagePreview: overrides.lastMessagePreview ?? '',
    lastResponsePreview: overrides.lastResponsePreview ?? '',
    createdAt: overrides.createdAt ?? '2026-05-18T00:00:00.000Z',
    updatedAt: overrides.updatedAt ?? '2026-05-18T00:00:00.000Z',
    lastMessageAt: overrides.lastMessageAt ?? null,
  };
}

test('resolveMergedConversationTitle keeps an explicit title when the incoming title is the default placeholder', () => {
  assert.equal(resolveMergedConversationTitle('채팅 관리 / 유형 권한 관리', '새 대화'), '채팅 관리 / 유형 권한 관리');
});

test('mergeConversationItemsPreservingRequestedSession does not overwrite an explicit title with the default placeholder', () => {
  const previousItems = [
    createConversationSummary({
      sessionId: 'session-1',
      title: '채팅 관리 / 유형 권한 관리',
      updatedAt: '2026-05-18T00:00:05.000Z',
    }),
  ];
  const nextItems = [
    createConversationSummary({
      sessionId: 'session-1',
      title: '새 대화',
      updatedAt: '2026-05-18T00:00:10.000Z',
    }),
  ];

  const [mergedItem] = mergeConversationItemsPreservingRequestedSession(nextItems, previousItems, 'session-1');

  assert.ok(mergedItem);
  assert.equal(mergedItem.title, '채팅 관리 / 유형 권한 관리');
});
