import type { Task, TaskPriority } from '../types/task';

const toTaskPriority = (value: unknown): TaskPriority => {
  if (value === 0 || value === 1 || value === 2) {
    return value;
  }

  if (typeof value === 'number' && Number.isFinite(value)) {
    if (value <= 0) return 0;
    if (value === 1) return 1;
    return 2;
  }

  if (typeof value === 'string') {
    const raw = value.trim();
    if (raw === '0' || raw === '1' || raw === '2') {
      return Number(raw) as TaskPriority;
    }

    const lower = raw.toLowerCase();
    if (lower === 'low') return 0;
    if (lower === 'medium' || lower === 'mid') return 1;
    if (lower === 'high') return 2;
  }

  return 1;
};

const toIsoString = (value: unknown): string => {
  if (typeof value === 'string' && value.trim()) return value;
  if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString();
  if (typeof value === 'number' && Number.isFinite(value)) return new Date(value).toISOString();
  return new Date().toISOString();
};

export const normalizeTask = (task: any): Task => {
  const normalized: any = { ...(task ?? {}) };

  if (typeof normalized.id === 'string' && /^\d+$/.test(normalized.id)) {
    normalized.id = Number(normalized.id);
  }

  normalized.title = typeof normalized.title === 'string' ? normalized.title : String(normalized.title ?? '');
  normalized.priority = toTaskPriority(normalized.priority);
  normalized.isCompleted = typeof normalized.isCompleted === 'boolean' ? normalized.isCompleted : Boolean(normalized.isCompleted);
  normalized.createdAt = toIsoString(normalized.createdAt);
  normalized.updatedAt = toIsoString(normalized.updatedAt);

  if (normalized.parentTaskId === null) {
    normalized.parentTaskId = undefined;
  } else if (typeof normalized.parentTaskId === 'string' && /^\d+$/.test(normalized.parentTaskId)) {
    normalized.parentTaskId = Number(normalized.parentTaskId);
  }

  if (Array.isArray(normalized.subTasks)) {
    normalized.subTasks = normalized.subTasks.map(normalizeTask);
  } else {
    normalized.subTasks = [];
  }

  return normalized as Task;
};

export const normalizeTasks = (tasks: unknown): Task[] => {
  if (!Array.isArray(tasks)) return [];
  return tasks.map(normalizeTask);
};

