import type { AbstractIntlMessages } from "next-intl";

/**
 * The whole message file is serialised into the HTML of every page, because a
 * single NextIntlClientProvider in the locale layout hands it to the client.
 * On /signup that was 170KB of messages inside a 216KB document — most of it
 * strings that page can never render. The ad traffic this funnel depends on is
 * mostly phones inside an in-app webview, so that weight is not free.
 *
 * So the locale layout ships only the base set, and the areas that need more
 * add it from their own provider. A nested provider replaces the messages it
 * inherits rather than merging, which is why each one passes base + its own.
 */

/** The legal documents. 48KB, rendered only by the six pages under (public). */
const LEGAL_NAMESPACES = ["legalPages"] as const;

/** The signed-in areas. 98KB, never rendered by a logged-out visitor. */
const DASHBOARD_NAMESPACES = [
  "practitioner",
  "admin",
  "individual",
  "practiceManager",
] as const;

const NON_BASE_NAMESPACES: readonly string[] = [
  ...LEGAL_NAMESPACES,
  ...DASHBOARD_NAMESPACES,
];

/** Return only the named namespaces, preserving the original objects. */
export function pickMessages(
  messages: AbstractIntlMessages,
  namespaces: readonly string[]
): AbstractIntlMessages {
  const picked: Record<string, unknown> = {};
  for (const namespace of namespaces) {
    if (namespace in messages) picked[namespace] = messages[namespace];
  }
  return picked as AbstractIntlMessages;
}

/** Shared namespaces every route needs — what the locale layout ships. */
export function baseMessages(
  messages: AbstractIntlMessages
): AbstractIntlMessages {
  return pickMessages(
    messages,
    Object.keys(messages).filter(
      (namespace) => !NON_BASE_NAMESPACES.includes(namespace)
    )
  );
}

/** The base set plus the namespaces a particular area renders. */
export function messagesWith(
  messages: AbstractIntlMessages,
  extra: readonly string[]
): AbstractIntlMessages {
  return { ...baseMessages(messages), ...pickMessages(messages, extra) };
}

/** Everything the signed-in areas render. */
export function dashboardMessages(
  messages: AbstractIntlMessages
): AbstractIntlMessages {
  return messagesWith(messages, DASHBOARD_NAMESPACES);
}
