export const formatElapsedTime = (totalSeconds: number): string => {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  return [hours, minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
};

export const getElapsedSeconds = (startedAt: string, endedAt?: string | null): number => {
  const start = new Date(startedAt).getTime();
  if (Number.isNaN(start)) return 0;

  const end = endedAt ? new Date(endedAt).getTime() : Date.now();
  if (Number.isNaN(end)) return 0;

  return Math.max(0, Math.floor((end - start) / 1000));
};

export const getActiveTimeEntry = <T extends { startedAt: string; endedAt?: string | null }>(times: T[]): T | null => {
  return times.find((entry) => entry.startedAt && !entry.endedAt) ?? null;
};

export const getEntryDurationSeconds = (entry: { startedAt: string; endedAt?: string | null; duration?: number | null }): number => {
  if (entry.endedAt) {
    return entry.duration ?? getElapsedSeconds(entry.startedAt, entry.endedAt);
  }

  return getElapsedSeconds(entry.startedAt);
};

export const sortTaskTimes = <T extends { startedAt: string }>(times: T[]): T[] => {
  return [...times].sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
};
