import test from 'node:test';
import assert from 'node:assert/strict';
import {
  createWenfanConversationRecord,
  deleteWenfanConversationRecord,
  updateWenfanConversationRecord,
} from './wenfan-conversation-history';

type TestMessage = {
  role: 'assistant' | 'user';
  content?: string;
};

const introMessage: TestMessage = {
  role: 'assistant',
  content: '我是问翻小宝',
};

test('createWenfanConversationRecord creates history only from the new conversation action', () => {
  const record = createWenfanConversationRecord('conv-1', [introMessage]);

  assert.equal(record.id, 'conv-1');
  assert.equal(record.title, '新对话');
  assert.deepEqual(record.messages, [introMessage]);
});

test('updateWenfanConversationRecord updates an existing conversation without adding a question record', () => {
  const record = createWenfanConversationRecord('conv-1', [introMessage]);
  const messages: TestMessage[] = [
    introMessage,
    { role: 'user', content: '怎么新建产品？' },
    { role: 'assistant', content: '产品创建帮助' },
    { role: 'user', content: '怎么新建项目？' },
  ];

  const next = updateWenfanConversationRecord([record], 'conv-1', messages);

  assert.equal(next.length, 1);
  assert.equal(next[0]?.title, '怎么新建产品？');
  assert.deepEqual(next[0]?.messages, messages);
});

test('updateWenfanConversationRecord does not create history when there is no active conversation', () => {
  const messages: TestMessage[] = [introMessage, { role: 'user', content: '怎么新建产品？' }];

  assert.deepEqual(updateWenfanConversationRecord([], null, messages), []);
});

test('deleteWenfanConversationRecord removes a conversation history item', () => {
  const first = createWenfanConversationRecord('conv-1', [introMessage]);
  const second = createWenfanConversationRecord('conv-2', [introMessage]);

  assert.deepEqual(deleteWenfanConversationRecord([first, second], 'conv-1'), [second]);
});
