export type PibiRow = {
  id: string;
  measureName: string;
  orderedAt: string;
  completedAt: string | null;
};

export type PibiBatch = {
  orderedAt: string;
  rows: PibiRow[];
};

export function groupByBatch(rows: PibiRow[]): PibiBatch[] {
  const map = new Map<string, PibiRow[]>();
  for (const row of rows) {
    const key = row.orderedAt;
    if (!map.has(key)) map.set(key, []);
    map.get(key)!.push(row);
  }
  return Array.from(map.entries()).map(([orderedAt, rows]) => ({ orderedAt, rows }));
}

export function formatDate(iso: string | null): string {
  if (!iso) return "—";
  try {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return "—";
    return d.toLocaleDateString("en-GB", {
      day: "2-digit", month: "short", year: "numeric",
    });
  } catch {
    return "—";
  }
}

export function toDateInputValue(iso: string | null): string {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return "";
    const yyyy = d.getUTCFullYear();
    const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
    const dd = String(d.getUTCDate()).padStart(2, "0");
    return `${yyyy}-${mm}-${dd}`;
  } catch {
    return "";
  }
}

export function dateInputToIso(value: string): string | null {
  if (!value) return null;
  return new Date(`${value}T00:00:00.000Z`).toISOString();
}
