import type { Requirement } from './requirement';

export type RequirementDateSort = 'desc' | 'asc';

export function sortRequirementsByCreatedAt(
  requirements: Requirement[],
  direction: RequirementDateSort = 'desc',
): Requirement[] {
  const multiplier = direction === 'asc' ? 1 : -1;
  return [...requirements].sort((a, b) => compareRequirementCreatedAt(a, b) * multiplier);
}

function compareRequirementCreatedAt(a: Requirement, b: Requirement): number {
  const createdAtDiff = toTimestamp(a.createdAt) - toTimestamp(b.createdAt);
  if (createdAtDiff !== 0) return createdAtDiff;

  const idDiff = trailingNumber(a.id) - trailingNumber(b.id);
  if (idDiff !== 0) return idDiff;

  const codeDiff = trailingNumber(a.code) - trailingNumber(b.code);
  if (codeDiff !== 0) return codeDiff;

  const codeTextDiff = a.code.localeCompare(b.code);
  if (codeTextDiff !== 0) return codeTextDiff;

  return a.id.localeCompare(b.id);
}

function toTimestamp(value: string): number {
  const timestamp = new Date(value).getTime();
  return Number.isFinite(timestamp) ? timestamp : 0;
}

function trailingNumber(value: string): number {
  const matches = value.match(/\d+/g);
  if (!matches) return 0;
  const numericValue = Number(matches[matches.length - 1]);
  return Number.isFinite(numericValue) ? numericValue : 0;
}
