// Minimaler iCalendar-Generator (RFC 5545) — bewusst ohne externe Bibliothek,
// da nur einfache Termine (Titel, Zeitraum, Beschreibung) exportiert werden.
export type IcsEvent = {
  uid: string;
  title: string;
  description?: string;
  location?: string;
  start: Date;
  end?: Date | null;
  allDay?: boolean;
  url?: string;
};

function escapeText(value: string): string {
  return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\n/g, "\\n");
}

// RFC 5545 verlangt Zeilenumbruch nach spätestens 75 Oktetten, Folgezeilen
// beginnen mit einem Leerzeichen.
function foldLine(line: string): string {
  if (line.length <= 75) return line;
  const parts: string[] = [];
  let rest = line;
  while (rest.length > 75) {
    parts.push(rest.slice(0, 75));
    rest = " " + rest.slice(75);
  }
  parts.push(rest);
  return parts.join("\r\n");
}

function formatDateTimeUTC(d: Date): string {
  return d.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
}

function formatDateOnly(d: Date): string {
  return d.toISOString().slice(0, 10).replace(/-/g, "");
}

export function buildIcsFeed(calendarName: string, events: IcsEvent[]): string {
  const lines: string[] = [
    "BEGIN:VCALENDAR",
    "VERSION:2.0",
    "PRODID:-//Rakku Photography//Kalender//DE",
    "CALSCALE:GREGORIAN",
    "METHOD:PUBLISH",
    `X-WR-CALNAME:${escapeText(calendarName)}`,
    "REFRESH-INTERVAL;VALUE=DURATION:PT1H",
    "X-PUBLISHED-TTL:PT1H",
  ];

  const stamp = formatDateTimeUTC(new Date());
  for (const ev of events) {
    lines.push("BEGIN:VEVENT");
    lines.push(`UID:${ev.uid}@rakku.de`);
    lines.push(`DTSTAMP:${stamp}`);
    if (ev.allDay) {
      lines.push(`DTSTART;VALUE=DATE:${formatDateOnly(ev.start)}`);
      if (ev.end) lines.push(`DTEND;VALUE=DATE:${formatDateOnly(ev.end)}`);
    } else {
      lines.push(`DTSTART:${formatDateTimeUTC(ev.start)}`);
      lines.push(`DTEND:${formatDateTimeUTC(ev.end ?? new Date(ev.start.getTime() + 60 * 60 * 1000))}`);
    }
    lines.push(`SUMMARY:${escapeText(ev.title)}`);
    if (ev.description) lines.push(`DESCRIPTION:${escapeText(ev.description)}`);
    if (ev.location) lines.push(`LOCATION:${escapeText(ev.location)}`);
    if (ev.url) lines.push(`URL:${ev.url}`);
    lines.push("END:VEVENT");
  }

  lines.push("END:VCALENDAR");
  return lines.map(foldLine).join("\r\n") + "\r\n";
}
