import type { SiteAdminFormat } from "../context";

/** Same shape as the dashboard's `MEDIUM_DATE_FORMAT`. */
const MEDIUM_DATE: Intl.DateTimeFormatOptions = {
  year: "numeric",
  month: "short",
  day: "numeric",
};

// The `"always"` string predates the repo's `ES2022` lib; every runtime the
// bundle targets supports it (as the dashboard's `formatCount`).
const COUNT_FORMAT = {
  useGrouping: "always",
} as unknown as Intl.NumberFormatOptions;

/** The dashboard's formatters, with `Intl` and the browser's timezone. */
export function createFormat(intlLocale: string): SiteAdminFormat {
  const date: SiteAdminFormat["date"] = (value, options) =>
    new Intl.DateTimeFormat(intlLocale, options ?? MEDIUM_DATE).format(
      new Date(value),
    );
  return {
    intlLocale,
    date,
    customerDate: (value, options) =>
      date(value, { ...(options ?? MEDIUM_DATE), timeZone: "Europe/Rome" }),
    count: (value) =>
      new Intl.NumberFormat(intlLocale, COUNT_FORMAT).format(value),
    currency: (value, currency, options) =>
      new Intl.NumberFormat(intlLocale, {
        ...COUNT_FORMAT,
        ...options,
        style: "currency",
        currency,
      }).format(value),
  };
}
