import { LabTaskStatus } from '@prisma/client';

/** Parse YYYY-MM-DD (or ISO) into UTC midnight for that calendar day. */
export function parseDueDateInput(value?: string | null): Date | null {
  if (value === undefined || value === null || value === '') {
    return null;
  }
  const trimmed = value.trim();
  if (!trimmed) return null;

  const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(trimmed);
  const parsed = dateOnly ? new Date(`${trimmed}T00:00:00.000Z`) : new Date(trimmed);
  if (Number.isNaN(parsed.getTime())) {
    throw new Error('Invalid due date');
  }
  if (dateOnly) {
    return parsed;
  }
  const normalized = new Date(parsed);
  normalized.setUTCHours(0, 0, 0, 0);
  return normalized;
}

export function startOfUtcDay(date = new Date()): Date {
  const d = new Date(date);
  d.setUTCHours(0, 0, 0, 0);
  return d;
}

export function isLabCaseOverdue(
  dueDate: Date | null | undefined,
  tasks: Array<{ status: LabTaskStatus }>,
): boolean {
  if (!dueDate) return false;
  const hasInProgress = tasks.some((task) => task.status === LabTaskStatus.IN_PROGRESS);
  if (!hasInProgress) return false;
  return dueDate < startOfUtcDay();
}

export function isLabCaseFullyCompleted(tasks: Array<{ status: LabTaskStatus }>): boolean {
  return tasks.length > 0 && tasks.every((task) => task.status === LabTaskStatus.COMPLETED);
}
