import { describe, it, expect } from 'vitest';
import { sortSpacesForRail } from './spaceSort';
import type { Space } from '../api';

function mk(partial: Partial<Space>): Space {
  return {
    id: 'x',
    kind: 'case',
    title: '',
    description: '',
    ownerId: null,
    visibility: 'private',
    visibilityScopeOrgId: null,
    status: 'open',
    brandColor: null,
    workspaceDir: null,
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
    ...partial,
  };
}

describe('sortSpacesForRail', () => {
  it('pins the personal space first regardless of updatedAt', () => {
    const result = sortSpacesForRail([
      mk({ id: 'c1', kind: 'case', updatedAt: '2026-06-18T00:00:00Z' }),
      mk({ id: 'me', kind: 'personal', updatedAt: '2026-01-01T00:00:00Z' }),
    ]);
    expect(result[0].id).toBe('me');
  });

  it('orders cases by updatedAt descending', () => {
    const result = sortSpacesForRail([
      mk({ id: 'old', updatedAt: '2026-01-01T00:00:00Z' }),
      mk({ id: 'new', updatedAt: '2026-06-18T00:00:00Z' }),
      mk({ id: 'mid', updatedAt: '2026-03-01T00:00:00Z' }),
    ]);
    expect(result.map(s => s.id)).toEqual(['new', 'mid', 'old']);
  });

  it('does not mutate the input array', () => {
    const input = [mk({ id: 'a' }), mk({ id: 'me', kind: 'personal' })];
    const before = input.map(s => s.id);
    sortSpacesForRail(input);
    expect(input.map(s => s.id)).toEqual(before);
  });
});
