import {
  getLocaleOption,
  type SupportedLocale,
} from "@/lib/i18n-config";

export const PUBLIC_PREFIXED_LOCALES = ["en", "zh", "ja", "vi", "ru"] as const;

export function getLocalizedPublicPath(pathname: string, locale: SupportedLocale) {
  const normalizedPath = pathname.startsWith("/") ? pathname : `/${pathname}`;

  if (locale === "ko") {
    return normalizedPath;
  }

  return normalizedPath === "/" ? `/${locale}` : `/${locale}${normalizedPath}`;
}

export function getPublicLanguageAlternates(pathname: string, origin: string) {
  const locales: SupportedLocale[] = ["ko", ...PUBLIC_PREFIXED_LOCALES];
  const languages = Object.fromEntries(
    locales.map((locale) => [
      getLocaleOption(locale).htmlLang,
      new URL(getLocalizedPublicPath(pathname, locale), origin).toString(),
    ]),
  );

  return {
    ...languages,
    "x-default": new URL(
      getLocalizedPublicPath(pathname, "ko"),
      origin,
    ).toString(),
  };
}

export function parseLocalizedPublicPath(pathname: string) {
  for (const locale of PUBLIC_PREFIXED_LOCALES) {
    if (pathname === `/${locale}`) {
      return { locale, pathname: "/" };
    }

    if (pathname.startsWith(`/${locale}/`)) {
      return { locale, pathname: pathname.slice(locale.length + 1) || "/" };
    }
  }

  return null;
}
