import test from 'node:test'
import assert from 'node:assert/strict'

import {
  filterConversations,
  getStorageKey,
  saveConversation,
  getConversations,
} from './chatHistory.js'

function installLocalStorage() {
  const store = new Map()
  globalThis.localStorage = {
    getItem: (key) => store.has(key) ? store.get(key) : null,
    setItem: (key, value) => store.set(key, String(value)),
    removeItem: (key) => store.delete(key),
    clear: () => store.clear(),
  }
  return store
}

test('getStorageKey isolates conversations by user identity', () => {
  const alice = { email: 'alice@example.com', phone: '13100000000' }
  const bob = { email: 'bob@example.com', phone: '13200000000' }

  assert.notEqual(getStorageKey('create', alice), getStorageKey('create', bob))
  assert.match(getStorageKey('create', alice), /^chat_conversations_create_/)
})

test('saveConversation and getConversations do not mix users', () => {
  installLocalStorage()

  saveConversation('create', {
    skillName: 'Alice Skill',
    messages: [
      { role: 'assistant', content: 'hello' },
      { role: 'user', content: '创建 Alice 专用 Skill' },
    ],
  }, { email: 'alice@example.com' })
  saveConversation('create', {
    skillName: 'Bob Skill',
    messages: [
      { role: 'assistant', content: 'hello' },
      { role: 'user', content: '创建 Bob 专用 Skill' },
    ],
  }, { email: 'bob@example.com' })

  assert.deepEqual(getConversations('create', { email: 'alice@example.com' }).map(c => c.skillName), ['Alice Skill'])
  assert.deepEqual(getConversations('create', { email: 'bob@example.com' }).map(c => c.skillName), ['Bob Skill'])
})

test('filterConversations matches title, preview, messages, and fuzzy characters', () => {
  const conversations = [
    {
      id: 'a',
      skillName: '合同审查助手',
      preview: '识别风险条款',
      sessionId: 'session-alpha',
      messages: [{ role: 'assistant', content: '输出红黄绿风险分级' }],
      updatedAt: 2,
    },
    {
      id: 'b',
      skillName: '会议纪要生成',
      preview: '从录音整理行动项',
      sessionId: 'session-beta',
      messages: [{ role: 'assistant', content: '包含责任人和截止时间' }],
      updatedAt: 1,
    },
  ]

  assert.deepEqual(filterConversations(conversations, '合同').map(c => c.id), ['a'])
  assert.deepEqual(filterConversations(conversations, '截止').map(c => c.id), ['b'])
  assert.deepEqual(filterConversations(conversations, 'hyjy').map(c => c.id), [])
  assert.deepEqual(filterConversations(conversations, '会纪').map(c => c.id), ['b'])
  assert.deepEqual(filterConversations(conversations, 'alpha').map(c => c.id), ['a'])
})
