// English only uses "one" and "other"
type EnglishCardinalRule = Extract<Intl.LDMLPluralRule, "one" | "other">;

export type AppkitFormatters = ReturnType<typeof createFormatters>;

// Currently, we only support localizing English variants.
type EnglishLocale = "en" | `en-${string}`;

/**
 * Creates formatters that can be used across the app.
 *
 * These can be either used directly when imported, or via the `useAppConfig`
 * hook when using inside of reusable components like e.g. the `SyncLog`.
 */
export function createFormatters(locale: EnglishLocale) {
  const cardinalRules = new Intl.PluralRules(locale);

  const dateTimeFmt = new Intl.DateTimeFormat(locale);

  const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: "long" });

  const conjunctionFmt = new Intl.ListFormat(locale, {
    style: "long",
    type: "conjunction",
  });

  const disjunctionFmt = new Intl.ListFormat(locale, {
    style: "long",
    type: "disjunction",
  });

  return {
    plural(count: number, rules: Record<EnglishCardinalRule, string>) {
      const tag = cardinalRules.select(count) as EnglishCardinalRule;
      return rules[tag].replace("#", count.toString());
    },
    dateTime(date: Date | string | number) {
      return dateTimeFmt.format(new Date(date));
    },
    date(date: Date | string | number) {
      return dateFmt.format(new Date(date));
    },
    conjunction(items: string[]) {
      return conjunctionFmt.format(items);
    },
    disjunction(items: string[]) {
      return disjunctionFmt.format(items);
    },
  };
}
