import type { Session } from "../services/attendance";

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("cs-CZ");
}

function formatTime(iso: string): string {
  return new Date(iso).toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" });
}

function formatDuration(ms: number): string {
  const totalMinutes = Math.round(ms / 60000);
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  return `${hours}:${String(minutes).padStart(2, "0")}`;
}

function escapeCsvField(value: string): string {
  return /[",\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
}

export function sessionsToCsv(sessions: Session[]): string {
  const header = ["Datum", "Příchod", "Odchod", "Pauza (h:mm)", "Odpracováno (h:mm)"];
  const rows = [...sessions]
    .sort((a, b) => a.clockIn.localeCompare(b.clockIn))
    .map((s) => [
      formatDate(s.clockIn),
      formatTime(s.clockIn),
      s.clockOut ? formatTime(s.clockOut) : "probíhá",
      formatDuration(s.breakMs),
      formatDuration(s.workedMs),
    ]);

  return [header, ...rows].map((row) => row.map(escapeCsvField).join(",")).join("\r\n");
}
