import { isDate } from '../shared/dates';
import { escapeHtml } from '../shared/ui';
import type { PlanTask } from './core';

/** Frappe 1.2.2 callbacks already subtract one second from the end boundary. */
export function dateFromFrappe(value: Date): string {
  if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new Error('Invalid timeline date.');
  const result = `${String(value.getFullYear()).padStart(4, '0')}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
  if (!isDate(result)) throw new Error('The timeline date is outside the supported range.');
  return result;
}

export function ganttTasks(tasks: PlanTask[]) {
  return tasks.map(task => ({
    id: task.id,
    // Frappe writes SVG text with innerHTML. Escape this copy, never saved data.
    name: escapeHtml(task.title.length > 90 ? `${task.title.slice(0, 87)}…` : task.title),
    start: task.start, end: task.end, progress: Number(task.progressPercent),
    dependencies: task.predecessors.join(','),
  }));
}
