import { parseISO, differenceInMinutes, isValid } from "date-fns";

/**
 * Diff (in minutes) between departure and arrival ISO UTC strings.
 * Returns null when either input is missing/invalid, or when result is negative.
 */
export function computeTransferMinutes(
  arrivalUtc: string | undefined,
  departureUtc: string | undefined,
): number | null {
  if (!arrivalUtc || !departureUtc) return null;
  const arr = parseISO(arrivalUtc);
  const dep = parseISO(departureUtc);
  if (!isValid(arr) || !isValid(dep)) return null;
  const diff = differenceInMinutes(dep, arr);
  if (diff < 0) return null;
  return diff;
}

/**
 * Format a minute count as "Nh Mm" (or "Mm" when <1 hour, or "Nh" when no remainder).
 */
export function formatMinutesAsDuration(minutes: number): string {
  if (minutes < 60) return `${minutes}m`;
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  if (m === 0) return `${h}h`;
  return `${h}h ${m}m`;
}
