export type Language = "ru" | "en" | "es" | "fr" | "it" | "ja" | "ko" | "zh" | "de";

export const LANGUAGES: readonly Language[] = [
  "ru", "en", "es", "fr", "it", "ja", "ko", "zh", "de",
] as const;

const languageSet: ReadonlySet<string> = new Set(LANGUAGES);

export function isLanguage(x: string): x is Language {
  return languageSet.has(x);
}

export function resolveLocaleFromPath(pathname: string): Language | null {
  const segments = pathname.split("/").filter(Boolean);
  const first = segments[0];
  if (first !== undefined && isLanguage(first)) {
    return first;
  }
  return null;
}

export function stripLocaleFromPath(
  pathname: string,
): { locale: Language; rest: string } | null {
  const locale = resolveLocaleFromPath(pathname);
  if (locale === null) return null;

  const rest = pathname.slice(`/${locale}`.length);
  return {
    locale,
    rest: rest === "" || rest === "/" ? "/" : rest,
  };
}
