import { describe, expect, it } from 'vitest'

import type { AgentState } from './agents'
import { replaceSavedState } from './variants'

function makeState(overrides: Partial<AgentState> & Pick<AgentState, 'id'>): AgentState {
	return {
		id: overrides.id,
		name: overrides.name ?? overrides.id,
		history: overrides.history ?? [],
		schedule: overrides.schedule ?? {},
		prev: overrides.prev ?? null,
		next: overrides.next ?? null
	}
}

describe('replaceSavedState', () => {
	it('replaces only the target state history and schedule', () => {
		const original = [
			makeState({ id: 'state-1', next: 'state-2' }),
			makeState({
				id: 'state-2',
				prev: 'state-1',
				history: [{ type: 'message', payload: { sender: 'user', text: 'old' } }] as any,
				schedule: { followUp: { at: 'tomorrow' } } as any
			})
		]

		const updated = replaceSavedState(original, 'state-2', {
			history: [{ type: 'message', payload: { sender: 'agent', text: 'new' } }] as any,
			schedule: { followUp: { at: null } } as any
		})

		expect(updated[0]).toEqual(original[0])
		expect(updated[1]).toMatchObject({
			id: 'state-2',
			name: 'state-2',
			prev: 'state-1',
			next: null,
			history: [{ type: 'message', payload: { sender: 'agent', text: 'new' } }],
			schedule: { followUp: { at: null } }
		})
	})

	it('throws when the requested state does not exist', () => {
		expect(() =>
			replaceSavedState([makeState({ id: 'state-1' })], 'missing', {
				history: [],
				schedule: {}
			})
		).toThrow('Could not find the target state to replace')
	})
})
