import test from 'node:test';
import assert from 'node:assert/strict';

import { orderByRequirementForGrouping } from './requirement-grouping';

interface GroupableItem {
  id: string;
  requirementId?: string;
  title?: string;
}

test('keeps later-created dev tasks beside existing tasks of the same requirement before pagination', () => {
  const tasks: GroupableItem[] = [
    { id: 'task-1', requirementId: 'req-1', title: 'existing req 1' },
    { id: 'task-2', requirementId: 'req-2', title: 'existing req 2' },
    { id: 'task-3', requirementId: 'req-3', title: 'existing req 3' },
    { id: 'task-4', requirementId: 'req-1', title: 'new req 1' },
  ];

  const ordered = orderByRequirementForGrouping(tasks, ['req-1', 'req-2', 'req-3'], (task: GroupableItem) => task.requirementId);

  assert.deepEqual(ordered.map((task: GroupableItem) => task.id), ['task-1', 'task-4', 'task-2', 'task-3']);
});

test('keeps unlinked test cases in a stable trailing group', () => {
  const cases: GroupableItem[] = [
    { id: 'tc-1', requirementId: 'req-2' },
    { id: 'tc-2', requirementId: undefined },
    { id: 'tc-3', requirementId: 'req-1' },
    { id: 'tc-4', requirementId: undefined },
  ];

  const ordered = orderByRequirementForGrouping(cases, ['req-1', 'req-2'], (testCase: GroupableItem) => testCase.requirementId);

  assert.deepEqual(ordered.map((testCase: GroupableItem) => testCase.id), ['tc-3', 'tc-1', 'tc-2', 'tc-4']);
});
