import { describe, expect, it } from 'vitest';
import { CanvasStore } from './canvas-store.js';

describe('CanvasStore', () => {
  it('stores and retrieves artifacts per session', () => {
    const store = new CanvasStore();
    const artifact = store.put('ws:1', {
      id: 'a1',
      type: 'note',
      content: { text: 'hello' },
    });

    expect(artifact.id).toBe('a1');
    expect(store.get('ws:1', 'a1')?.type).toBe('note');
    expect(store.list('ws:1')).toHaveLength(1);
  });

  it('updates existing artifacts while preserving createdAt', async () => {
    const store = new CanvasStore();
    const first = store.put('ws:1', {
      id: 'a1',
      type: 'note',
      content: { text: 'one' },
    });
    await new Promise((resolve) => setTimeout(resolve, 2));
    const second = store.put('ws:1', {
      id: 'a1',
      type: 'note',
      content: { text: 'two' },
    });

    expect(second.createdAt).toBe(first.createdAt);
    expect(second.updatedAt).toBeGreaterThanOrEqual(first.updatedAt);
    expect(store.get('ws:1', 'a1')?.content).toEqual({ text: 'two' });
  });

  it('deletes and clears session artifacts', () => {
    const store = new CanvasStore();
    store.put('ws:1', { id: 'a1', type: 'note', content: 'x' });
    store.put('ws:1', { id: 'a2', type: 'note', content: 'y' });

    expect(store.delete('ws:1', 'a1')).toBe(true);
    expect(store.delete('ws:1', 'missing')).toBe(false);
    expect(store.list('ws:1')).toHaveLength(1);
    expect(store.clear('ws:1')).toBe(1);
    expect(store.list('ws:1')).toEqual([]);
  });

  it('evicts oldest artifact when per-session cap is exceeded', () => {
    const store = new CanvasStore(2);
    store.put('ws:1', { id: 'a1', type: 'note', content: 1 });
    store.put('ws:1', { id: 'a2', type: 'note', content: 2 });
    store.put('ws:1', { id: 'a3', type: 'note', content: 3 });

    expect(store.get('ws:1', 'a1')).toBeUndefined();
    expect(store.list('ws:1').map((a) => a.id).sort()).toEqual(['a2', 'a3']);
  });
});
