import { describe, expect, it } from 'vitest';
import {
  buildTimelineGroups,
  getProductLabel,
  getTimelineStats,
  type TimelineItem,
} from '@/lib/timeline-view';

const baseItems: TimelineItem[] = [
  {
    itemId: 'timeline_1',
    occurredAt: '2026-04-04T10:02:00.000Z',
    eventName: 'artifact.created',
    productId: 'notelett',
    title: 'Note created',
    summary: 'Latest note',
    artifactRefs: ['art_note_1'],
    relatedEventIds: ['evt_2'],
    actorType: 'user',
    visibility: 'private',
    correlationId: 'corr_shared',
  },
  {
    itemId: 'timeline_2',
    occurredAt: '2026-04-04T10:01:00.000Z',
    eventName: 'capture.transcript.created',
    productId: 'lysnrai',
    title: 'Transcript captured',
    summary: null,
    artifactRefs: ['art_transcript_1'],
    relatedEventIds: [],
    actorType: 'user',
    visibility: 'private',
    correlationId: 'corr_shared',
  },
  {
    itemId: 'timeline_3',
    occurredAt: '2026-04-04T09:59:00.000Z',
    eventName: 'memory.entry.created',
    productId: 'mindlyst',
    title: 'Memory candidate proposed',
    summary: null,
    artifactRefs: [],
    relatedEventIds: [],
    actorType: 'agent',
    visibility: 'private',
    correlationId: null,
  },
];

describe('timeline view helpers', () => {
  it('groups correlation-linked items together and sorts them newest-first', () => {
    const groups = buildTimelineGroups(baseItems);

    expect(groups).toHaveLength(2);
    expect(groups[0]).toMatchObject({
      correlationId: 'corr_shared',
      latestOccurredAt: '2026-04-04T10:02:00.000Z',
      productIds: ['notelett', 'lysnrai'],
    });
    expect(groups[0]?.items.map(item => item.itemId)).toEqual(['timeline_1', 'timeline_2']);
  });

  it('computes timeline stats over grouped and ungrouped items', () => {
    expect(getTimelineStats(baseItems)).toEqual({
      uniqueProducts: 3,
      uniqueCorrelations: 1,
      withArtifacts: 2,
      groupedChains: 1,
    });
  });

  it('returns readable labels for known products', () => {
    expect(getProductLabel('lysnrai')).toBe('LysnrAI');
    expect(getProductLabel('custom-tool')).toBe('custom-tool');
  });
});
