import type { CalendarDoc } from "@/models/Calendar";

// "orders": nur sichtbar mit der "orders"-Berechtigung, nie manuell editierbar
// (Termine werden über die jeweilige Auftragsseite gesetzt).
// "absences": für jedes eingeloggte Team-Mitglied sichtbar, genau wie die
// Abwesenheits-Seite selbst (kein eigenes Berechtigungsfeld) — nie manuell
// editierbar, Einträge kommen nur über /admin/absences zustande.
// "custom": sichtbar für den Ersteller, alle in sharedWith gelisteten
// Mitarbeiter, und bei visibility "team" für jeden mit der
// "calendars"-Berechtigung — bearbeitbar nur für Ersteller + sharedWith.
export function canViewCalendar(
  cal: Pick<CalendarDoc, "kind" | "ownerId" | "visibility" | "sharedWith">,
  clientId: string,
  hasOrders: boolean,
  hasCalendars: boolean
): boolean {
  if (cal.kind === "orders") return hasOrders;
  if (cal.kind === "absences") return true;
  if (cal.kind === "conventions") return true;
  if (!hasCalendars) return false;
  if (cal.visibility === "team") return true;
  return isOwnerOrShared(cal, clientId);
}

export function canEditCalendar(
  cal: Pick<CalendarDoc, "kind" | "ownerId" | "sharedWith">,
  clientId: string,
  hasCalendars: boolean
): boolean {
  if (cal.kind === "orders" || cal.kind === "absences" || cal.kind === "conventions") return false;
  if (!hasCalendars) return false;
  return isOwnerOrShared(cal, clientId);
}

function isOwnerOrShared(cal: Pick<CalendarDoc, "ownerId" | "sharedWith">, clientId: string): boolean {
  if (cal.ownerId && String(cal.ownerId) === clientId) return true;
  return cal.sharedWith.some((id) => String(id) === clientId);
}
