import dayjs from 'dayjs';

// Format a Unix timestamp (seconds) as the legacy host-page format:
// `YYYY-MM-DD HH:MM±HH:MM` (no seconds), or with seconds when `withSeconds`
// is true (matches the Measurements widget output).
//
// Returns `fallback` (default 'unknown') if the timestamp is falsy or invalid.
export interface FormatTimestampOptions {
  withSeconds?: boolean;
  fallback?: string;
}

export const formatTimestamp = (
  ts: number | null | undefined,
  { withSeconds = false, fallback = 'unknown' }: FormatTimestampOptions = {}
): string => {
  if (!ts) return fallback;
  const d = dayjs.unix(ts);
  if (!d.isValid()) return fallback;
  // `Z` renders the local UTC offset as ±HH:mm.
  return d.format(withSeconds ? 'YYYY-MM-DD HH:mm:ssZ' : 'YYYY-MM-DD HH:mmZ');
};
