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

import type { Requirement } from './requirement';
import { sortRequirementsByCreatedAt } from './requirement-sort';

const baseRequirement = {
  description: '',
  productId: 'product-1',
  projectId: 'project-1',
  sourceType: 'internal',
  sourceTarget: '',
  platforms: [] as string[],
  typeId: 'type-1',
  status: 'pending_review',
  priority: 'P2',
  effort: 'M',
  creator: 'tester',
};

function req(id: string, code: string, createdAt: string): Requirement {
  return {
    ...baseRequirement,
    id,
    code,
    title: code,
    createdAt,
  } as Requirement;
}

test('sorts requirements by created time descending by default', () => {
  const requirements = [
    req('req-100', 'REQ-001', '2026-06-28T09:00:00.000Z'),
    req('req-300', 'REQ-003', '2026-06-29T09:00:00.000Z'),
    req('req-200', 'REQ-002', '2026-06-28T18:00:00.000Z'),
  ];

  assert.deepEqual(sortRequirementsByCreatedAt(requirements).map((item) => item.id), ['req-300', 'req-200', 'req-100']);
});

test('uses id/code fallback when legacy requirements only have the same date', () => {
  const requirements = [
    req('req-1782301644000', 'REQ-010', '2026-06-24'),
    req('req-1782301644789', 'REQ-011', '2026-06-24'),
    req('req-old', 'REQ-009', '2026-06-24'),
  ];

  assert.deepEqual(sortRequirementsByCreatedAt(requirements).map((item) => item.id), [
    'req-1782301644789',
    'req-1782301644000',
    'req-old',
  ]);
});

test('can sort requirements by created time ascending', () => {
  const requirements = [
    req('req-300', 'REQ-003', '2026-06-29T09:00:00.000Z'),
    req('req-100', 'REQ-001', '2026-06-28T09:00:00.000Z'),
    req('req-200', 'REQ-002', '2026-06-28T18:00:00.000Z'),
  ];

  assert.deepEqual(sortRequirementsByCreatedAt(requirements, 'asc').map((item) => item.id), ['req-100', 'req-200', 'req-300']);
});
