/**
 * RRULE building and parsing helpers.
 */

export type RepeatType = "Tag" | "Woche" | "Monat" | "Jahr";

const REPEAT_TYPE_TO_FREQ: Record<RepeatType, string> = {
  Tag: "DAILY",
  Woche: "WEEKLY",
  Monat: "MONTHLY",
  Jahr: "YEARLY",
};

const FREQ_TO_REPEAT_TYPE: Record<string, RepeatType> = Object.fromEntries(
  Object.entries(REPEAT_TYPE_TO_FREQ).map(([k, v]) => [v, k as RepeatType]),
);

export const REPEAT_TYPE_LABELS: Record<RepeatType, string> = {
  Tag: "Tage",
  Woche: "Wochen",
  Monat: "Monate",
  Jahr: "Jahre",
};

const REPEAT_TYPE_SINGULAR: Record<RepeatType, string> = {
  Tag: "Jeden Tag",
  Woche: "Jede Woche",
  Monat: "Jeden Monat",
  Jahr: "Jedes Jahr",
};

/**
 * Build an RRULE string from repeat count and type.
 *
 * @param repeatType - The type of repetition (Tag, Woche, Monat, Jahr)
 * @param interval - The interval between repetitions (default: 1)
 * @returns RRULE string like "FREQ=WEEKLY;INTERVAL=2"
 */
export function buildRRule(
  repeatType: RepeatType,
  interval: number = 1,
): string {
  const freq = REPEAT_TYPE_TO_FREQ[repeatType];

  if (interval <= 1) {
    return `FREQ=${freq}`;
  }

  return `FREQ=${freq};INTERVAL=${interval}`;
}

/**
 * Format an RRULE string into a human-readable German description.
 *
 * @param rrule - RRULE string like "FREQ=WEEKLY;INTERVAL=2"
 * @returns German description like "Alle 2 Wochen" or "Wöchentlich"
 */
export function formatRecurrenceRule(rrule: string): string {
  const rule = rrule.replace(/^RRULE:/, "");
  const parts = Object.fromEntries(
    rule.split(";").map((p) => p.split("=") as [string, string]),
  );

  const freq = parts.FREQ;
  const interval = parts.INTERVAL ? parseInt(parts.INTERVAL, 10) : 1;
  const repeatType = FREQ_TO_REPEAT_TYPE[freq];

  if (!repeatType) {
    return "Wiederkehrend";
  }

  if (interval <= 1) {
    return REPEAT_TYPE_SINGULAR[repeatType];
  }

  return `Alle ${interval} ${REPEAT_TYPE_LABELS[repeatType]}`;
}
