import type { BackendTask } from '@/types';

const EXECUTING_TASK_STATUSES = new Set(['open', 'queued', 'running']);
const FINISHED_FOR_DURATION_STATUSES = new Set(['awaiting_acceptance', 'closed', 'abandoned', 'cancelled', 'error']);

export function shouldPollTaskDetail(task: Pick<BackendTask, 'status'> | null): boolean {
  return Boolean(task && EXECUTING_TASK_STATUSES.has(task.status));
}

export function taskDetailDurationMs(task: Pick<BackendTask, 'created_at' | 'updated_at' | 'closed_at' | 'status'>): number | null {
  const start = new Date(task.created_at).getTime();
  const end = FINISHED_FOR_DURATION_STATUSES.has(task.status)
    ? new Date(task.closed_at || task.updated_at).getTime()
    : Date.now();

  if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
  return Math.max(0, end - start);
}
