type DateInput = Date | string | number | null | undefined;

const pad2 = (value: number) => String(value).padStart(2, '0');

const toDate = (input: DateInput): Date | null => {
  if (input == null) return null;

  if (input instanceof Date) {
    return Number.isNaN(input.getTime()) ? null : input;
  }

  const date = new Date(input);
  return Number.isNaN(date.getTime()) ? null : date;
};

/**
 * Format datetime to `d-m-Y H:i` (e.g. `07-04-2026 14:05`).
 * Uses local time.
 */
export const formatDateTime = (input: DateInput, fallback = '-') => {
  const date = toDate(input);
  if (!date) return fallback;

  const day = pad2(date.getDate());
  const month = pad2(date.getMonth() + 1);
  const year = String(date.getFullYear());
  const hours = pad2(date.getHours());
  const minutes = pad2(date.getMinutes());

  return `${day}-${month}-${year} ${hours}:${minutes}`;
};
