/**
 * Transient state reset matrix tests (U5 / Bug 1).
 *
 * Verifies that createConversation / selectConversation / deleteConversation
 * reset the three stream-owned transient state refs (boardState /
 * debateState / collaborationState) to null — preventing cross-conversation
 * state leakage (e.g. private board header persisting into a new conversation).
 *
 * Mock strategy follows chat-phase.test.ts: mock apiClient + peer stores,
 * use setActivePinia(createPinia()), dynamic-import the real useChatStore.
 * All test conversations are is_local=true so no API calls fire.
 */

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'

// Mock apiClient so the store never touches the network.
vi.mock('@/api/client', () => ({
  apiClient: {
    getConversations: vi.fn().mockResolvedValue([]),
    getConversation: vi.fn().mockResolvedValue({ id: '', title: '', messages: [] }),
    deleteConversation: vi.fn().mockResolvedValue(undefined),
    get: vi.fn(),
    post: vi.fn(),
    put: vi.fn(),
    delete: vi.fn(),
    patch: vi.fn(),
  },
}))

// Mock peer stores to avoid pulling their dependencies.
vi.mock('@/stores/team', () => ({ useTeamStore: vi.fn(() => null) }))
vi.mock('@/stores/documents', () => ({ useDocumentsStore: vi.fn(() => null) }))
vi.mock('@/stores/calendar', () => ({ useCalendarStore: vi.fn(() => null) }))
vi.mock('@/api/documents', () => ({ isDocumentMeta: vi.fn() }))

describe('transient state reset matrix', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  it('createConversation resets boardState / debateState / collaborationState to null', async () => {
    const { useChatStore } = await import('@/stores/chatStore')
    const store = useChatStore()

    // Simulate a board meeting was active in the previous conversation.
    store.boardState = { topic: 'stale', experts: [], max_rounds: 1, current_round: 0, status: 'discussing' } as never
    store.debateState = { topic: 'stale' } as never
    store.collaborationState = { contracts: [], notices: [], reviews: [], risks: [] } as never

    store.createConversation()

    expect(store.boardState).toBeNull()
    expect(store.debateState).toBeNull()
    expect(store.collaborationState).toBeNull()
  })

  it('selectConversation to a different conversation resets all three states', async () => {
    const { useChatStore } = await import('@/stores/chatStore')
    const store = useChatStore()

    // Pre-populate two local conversations.
    store.conversations = [
      { id: 'conv-a', title: 'A', messages: [], created_at: '', updated_at: '', is_local: true },
      { id: 'conv-b', title: 'B', messages: [], created_at: '', updated_at: '', is_local: true },
    ]
    store.currentConversationId = 'conv-a'

    // Simulate board state from conversation A.
    store.boardState = { topic: 'board in A', experts: [], max_rounds: 1, current_round: 0, status: 'discussing' } as never
    store.debateState = { topic: 'debate in A' } as never
    store.collaborationState = { contracts: [], notices: [], reviews: [], risks: [] } as never

    // Switch to conversation B (no board messages → restoreBoardStateFromMessages returns null).
    await store.selectConversation('conv-b')

    expect(store.boardState).toBeNull()
    expect(store.debateState).toBeNull()
    expect(store.collaborationState).toBeNull()
  })

  it('selectConversation force-reload same id does not clear via conditional reset', async () => {
    const { useChatStore } = await import('@/stores/chatStore')
    const { restoreBoardStateFromMessages } = await import('@/stores/chatStore')

    // Build a conversation with a board_started message so restoreBoardStateFromMessages returns non-null.
    const boardStartedMsg = {
      id: 'msg-start',
      role: 'assistant' as const,
      content: '私董会开始：测试主题',
      timestamp: '2026-07-01T10:00:00Z',
      status: 'completed' as const,
      message_type: 'board_started' as const,
      board_started: {
        team_id: 'team-1',
        topic: '测试主题',
        max_rounds: 3,
        experts: [
          { name: 'Alice', avatar: 'A', color: '#888888', is_moderator: true, persona: '主持人' },
        ],
      },
      board_round: 0,
    }

    const store = useChatStore()
    store.conversations = [
      { id: 'conv-a', title: 'A', messages: [boardStartedMsg], created_at: '', updated_at: '', is_local: true },
    ]
    store.currentConversationId = 'conv-a'

    // Initial select to populate boardState from messages.
    await store.selectConversation('conv-a')
    expect(store.boardState).not.toBeNull()
    expect(store.boardState?.topic).toBe('测试主题')

    // Force-reload the same conversation — boardState should be restored, not cleared.
    await store.selectConversation('conv-a', true)
    expect(store.boardState).not.toBeNull()
    expect(store.boardState?.topic).toBe('测试主题')

    // Sanity: restoreBoardStateFromMessages returns non-null for this fixture.
    expect(restoreBoardStateFromMessages([boardStartedMsg])).not.toBeNull()
  })

  it('deleteConversation of current conversation resets all three states including collaborationState', async () => {
    const { useChatStore } = await import('@/stores/chatStore')
    const store = useChatStore()

    // Create a local conversation and select it.
    store.conversations = [
      { id: 'conv-a', title: 'A', messages: [], created_at: '', updated_at: '', is_local: true },
      { id: 'conv-b', title: 'B', messages: [], created_at: '', updated_at: '', is_local: true },
    ]
    store.currentConversationId = 'conv-a'

    // Simulate all three transient states are active.
    store.boardState = { topic: 'board', experts: [], max_rounds: 1, current_round: 0, status: 'discussing' } as never
    store.debateState = { topic: 'debate' } as never
    store.collaborationState = { contracts: [], notices: [], reviews: [], risks: [] } as never

    // Delete the current conversation — should reset all three states.
    await store.deleteConversation('conv-a')

    expect(store.boardState).toBeNull()
    expect(store.debateState).toBeNull()
    expect(store.collaborationState).toBeNull()
  })

  it('deleteConversation of a non-current conversation does not touch transient states', async () => {
    const { useChatStore } = await import('@/stores/chatStore')
    const store = useChatStore()

    store.conversations = [
      { id: 'conv-a', title: 'A', messages: [], created_at: '', updated_at: '', is_local: true },
      { id: 'conv-b', title: 'B', messages: [], created_at: '', updated_at: '', is_local: true },
    ]
    store.currentConversationId = 'conv-a'

    const boardState = { topic: 'board in A', experts: [], max_rounds: 1, current_round: 0, status: 'discussing' as const }
    store.boardState = boardState
    store.debateState = { topic: 'debate' } as never
    store.collaborationState = { contracts: [], notices: [], reviews: [], risks: [] } as never

    // Delete a non-current conversation — states should be untouched.
    await store.deleteConversation('conv-b')

    expect(store.boardState).not.toBeNull()
    expect(store.boardState?.topic).toBe('board in A')
    expect(store.debateState).not.toBeNull()
    expect(store.collaborationState).not.toBeNull()
  })
})
