import { afterEach, beforeEach, describe, expect, it } from 'vitest';

import { useChatStore } from '@/lib/store';

describe('chat store process event ingestion', () => {
  beforeEach(() => {
    useChatStore.setState({
      sessionId: 'web:alpha',
      inputDrafts: {},
      processRuns: [],
      processEvents: [],
      processArtifacts: [],
      selectedRunId: null,
      selectedArtifactId: null,
      lastCancelAck: null,
    });
  });

  afterEach(() => {
    useChatStore.setState({
      sessionId: 'web:default',
      inputDrafts: {},
      processRuns: [],
      processEvents: [],
      processArtifacts: [],
      selectedRunId: null,
      selectedArtifactId: null,
      lastCancelAck: null,
    });
  });

  it('assigns session_id when the first observed event is progress', () => {
    useChatStore.getState().ingestProcessEvent({
      type: 'process_run_progress',
      session_id: 'web:alpha',
      run_id: 'run-progress-only',
      parent_run_id: null,
      actor_type: 'agent',
      actor_id: 'agent-a',
      actor_name: 'Agent A',
      text: 'still working',
      created_at: '2026-03-24T11:20:00.000Z',
    });

    expect(useChatStore.getState().processRuns).toEqual([
      expect.objectContaining({
        run_id: 'run-progress-only',
        session_id: 'web:alpha',
        status: 'running',
        title: 'Agent A',
      }),
    ]);
  });

  it('stores input drafts per session', () => {
    useChatStore.getState().setInputDraft('web:alpha', 'message for alpha');
    useChatStore.getState().setInputDraft('web:beta', 'message for beta');

    expect(useChatStore.getState().getInputDraft('web:alpha')).toBe('message for alpha');
    expect(useChatStore.getState().getInputDraft('web:beta')).toBe('message for beta');

    useChatStore.getState().clearInputDraft('web:alpha');

    expect(useChatStore.getState().getInputDraft('web:alpha')).toBe('');
    expect(useChatStore.getState().getInputDraft('web:beta')).toBe('message for beta');
  });

  it('keeps live task events after persisted session projection is merged', () => {
    const store = useChatStore.getState();
    store.setSessionId('web:default');
    store.ingestProcessEvent({
      type: 'process_run_progress',
      session_id: 'web:default',
      run_id: 'run-live',
      parent_run_id: null,
      actor_type: 'agent',
      actor_id: 'main-agent',
      actor_name: 'Main Agent',
      text: '正在调用工具',
      metadata: { task_id: 'task-live', timeline_type: 'tool_call' },
      created_at: '2026-05-26T10:00:00.000Z',
    });

    store.setSessionProcess('web:default', {
      runs: [],
      events: [],
      artifacts: [],
    });

    expect(useChatStore.getState().processEvents.some((event) => event.run_id === 'run-live')).toBe(true);
  });
});
