import { describe, expect, it } from 'vitest'
import { buildAgentHistory } from '@/lib/domain/chat-history'

describe('Logistics Bot chat history', () => {
  it('pairs answers to questions and sends only the latest two completed turns', () => {
    const history = buildAgentHistory([
      { id: 'q1', is_ai: false, content: 'First?', answer_to_message_id: null },
      { id: 'a1', is_ai: true, content: 'First answer', answer_to_message_id: 'q1' },
      { id: 'q2', is_ai: false, content: 'Second?', answer_to_message_id: null },
      { id: 'a2', is_ai: true, content: 'Second answer', answer_to_message_id: 'q2' },
      { id: 'q3', is_ai: false, content: 'Third?', answer_to_message_id: null },
      { id: 'a3', is_ai: true, content: 'Third answer', answer_to_message_id: 'q3' },
      { id: 'q4', is_ai: false, content: 'Still unanswered', answer_to_message_id: null },
    ])

    expect(history).toEqual([
      { user: 'Second?', assistant: 'Second answer' },
      { user: 'Third?', assistant: 'Third answer' },
    ])
  })

  it('supports old rows whose answer does not have an explicit question link', () => {
    expect(buildAgentHistory([
      { id: 'q1', is_ai: false, content: 'Do I need escorts?', answer_to_message_id: null },
      { id: 'a1', is_ai: true, content: 'Yes.', answer_to_message_id: null },
    ])).toEqual([{ user: 'Do I need escorts?', assistant: 'Yes.' }])
  })
})
