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

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");
}

function payrollStatusLabel(row: PayrollOverviewRow): string {
  if (row.payroll_status === "paid") return "vyplaceno";
  if (row.payroll_status === "ready") return "připraveno k výplatě";
  if (row.closure_status === "confirmed") return "potvrzeno zaměstnancem";
  if (row.closure_status === "locked") return "uzamčeno";
  return "čeká na zaměstnance";
}

export function payrollToCsv(rows: PayrollOverviewRow[]): string {
  const header = [
    "Zaměstnanec",
    "Odpracováno (h:mm)",
    "Základ",
    "Spropitné",
    "Bonusy",
    "Ostatní",
    "Celkem",
    "Stav",
    "Datum výplaty",
  ];
  const body = rows.map((r) => [
    r.employee_name,
    formatDuration(r.worked_minutes * 60_000),
    r.base_amount.toFixed(2),
    r.tips_amount.toFixed(2),
    r.bonus_amount.toFixed(2),
    r.other_amount.toFixed(2),
    r.final_amount.toFixed(2),
    payrollStatusLabel(r),
    r.payment_date ?? "",
  ]);

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