export const TASK_RESULT_TIMEOUT_MS = 2 * 60 * 1000;

type TimedTask = {
  created_at: string;
  phase_started_at?: string;
  last_result_at?: string;
};

function timestamp(value?: string) {
  const parsed = value ? Date.parse(value) : Number.NaN;
  return Number.isFinite(parsed) ? parsed : 0;
}

export function taskActivityAt(task?: TimedTask) {
  if (!task) return 0;
  return timestamp(task.phase_started_at) || timestamp(task.last_result_at) || timestamp(task.created_at);
}

export function taskTimedOut(task: TimedTask | undefined, now: number) {
  const activityAt = taskActivityAt(task);
  return activityAt > 0 && now - activityAt >= TASK_RESULT_TIMEOUT_MS;
}

export function taskElapsedLabel(task: TimedTask | undefined, now: number) {
  const activityAt = taskActivityAt(task);
  const elapsed = activityAt > 0 ? Math.max(0, Math.floor((now - activityAt) / 1000)) : 0;
  const minutes = Math.floor(elapsed / 60)
    .toString()
    .padStart(2, "0");
  const seconds = (elapsed % 60).toString().padStart(2, "0");
  return `${minutes}:${seconds}`;
}
