import { describe, expect, it } from 'vitest'
import {
  initialIntelligentEvalReadState,
  intelligentEvalReadReducer,
  type IntelligentEvalReadState,
} from './intelligentEval'

const evaluation = { id: 'eval-1', name: '评估', status: 'planning' } as never

describe('intelligent evaluation read state', () => {
  it('represents initial loading and a complete list snapshot', () => {
    const loading = intelligentEvalReadReducer(initialIntelligentEvalReadState, { type: 'list_requested' })
    expect(loading.list.phase).toBe('loading')

    const ready = intelligentEvalReadReducer(loading, { type: 'list_succeeded', value: [evaluation] })
    expect(ready.list).toEqual({ phase: 'ready', value: [evaluation], error: null })
  })

  it('keeps the last list snapshot during silent refresh and failure', () => {
    const ready: IntelligentEvalReadState = {
      ...initialIntelligentEvalReadState,
      list: { phase: 'ready', value: [evaluation], error: null },
    }
    const refreshing = intelligentEvalReadReducer(ready, { type: 'list_requested', silent: true })
    expect(refreshing.list.phase).toBe('refreshing')

    const afterFailure = intelligentEvalReadReducer(refreshing, { type: 'list_failed', error: '网络错误' })
    expect(afterFailure.list).toEqual({ phase: 'ready', value: [evaluation], error: null })
  })

  it('surfaces an initial detail failure without an existing snapshot', () => {
    const loading = intelligentEvalReadReducer(initialIntelligentEvalReadState, {
      type: 'detail_requested',
      id: 'eval-1',
      requestId: 1,
    })
    const failed = intelligentEvalReadReducer(loading, {
      type: 'detail_failed',
      id: 'eval-1',
      requestId: 1,
      error: '不存在',
    })
    expect(failed.detail).toEqual({
      phase: 'error',
      value: null,
      error: '不存在',
      selectedId: 'eval-1',
      requestId: 1,
    })
  })

  it('ignores a stale detail response after the selection changes', () => {
    const first = intelligentEvalReadReducer(initialIntelligentEvalReadState, {
      type: 'detail_requested',
      id: 'eval-1',
      requestId: 1,
    })
    const second = intelligentEvalReadReducer(first, {
      type: 'detail_requested',
      id: 'eval-2',
      requestId: 2,
    })
    const stale = intelligentEvalReadReducer(second, {
      type: 'detail_succeeded',
      id: 'eval-1',
      requestId: 1,
      value: evaluation,
    })

    expect(stale).toBe(second)
    expect(stale.detail.value).toBeNull()
    expect(stale.detail.selectedId).toBe('eval-2')
  })
})
