import { describe, expect, it } from 'bun:test';
import { upsertWorkspaceRecord } from './useResearchWorkspaces';
import type { ResearchWorkspace } from '../types/research';

const createWorkspace = (id: string, ticker: string): ResearchWorkspace => ({
  id,
  name: `${ticker} Research`,
  primaryTicker: ticker,
  scope: 'single_company',
  stage: 'capture',
  defaultView: 'canvas',
  pinnedNoteIds: [],
  archived: false,
  createdAt: '2026-04-09T10:00:00Z',
  updatedAt: '2026-04-09T10:00:00Z',
});

describe('upsertWorkspaceRecord', () => {
  it('inserts new workspaces at the front of the list', () => {
    const current = [createWorkspace('workspace-1', 'AAPL')];
    const next = upsertWorkspaceRecord(current, createWorkspace('workspace-2', 'NVDA'));

    expect(next.map((workspace) => workspace.id)).toEqual(['workspace-2', 'workspace-1']);
  });

  it('updates existing workspaces in place by id', () => {
    const current = [createWorkspace('workspace-1', 'AAPL')];
    const next = upsertWorkspaceRecord(current, {
      ...createWorkspace('workspace-1', 'AAPL'),
      name: 'Apple Core Research',
    });

    expect(next).toHaveLength(1);
    expect(next[0].name).toBe('Apple Core Research');
  });
});
