import type { TargetStatus } from "../../shared/api";

const STATUS_ORDER: Record<string, number> = {
  down: 0,
  up: 1,
};

export function availabilitySorter(a: TargetStatus, b: TargetStatus): number {
  return (a.stats?.availability ?? 0) - (b.stats?.availability ?? 0);
}

export function latencySorter(a: TargetStatus, b: TargetStatus): number {
  return (a.latestCheck?.durationMs ?? Infinity) - (b.latestCheck?.durationMs ?? Infinity);
}

export function statusSorter(a: TargetStatus, b: TargetStatus): number {
  return getStatusRank(a) - getStatusRank(b);
}

function getStatusRank(target: TargetStatus): number {
  if (!target.latestCheck) return 2;
  return target.latestCheck.matched ? STATUS_ORDER["up"]! : STATUS_ORDER["down"]!;
}
