import { appLocales } from "../i18n/routing";

export type AppLocale = (typeof appLocales)[number];

export const FALLBACK_LOCALE: AppLocale = "de";

export function isSupportedLocale(locale: string | undefined | null): locale is AppLocale {
  return locale === "de" || locale === "en" || locale === "ar";
}

export function resolveLocale(locale: string | undefined | null, fallbackLocale: AppLocale): AppLocale {
  return isSupportedLocale(locale) ? locale : fallbackLocale;
}

export function getDirection(locale: string): "ltr" | "rtl" {
  return locale === "ar" ? "rtl" : "ltr";
}

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

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

  return pathname || "/";
}

export function getLocalizedPath(
  locale: string,
  pathname = "/",
  defaultLocale: AppLocale,
): string {
  return getLocalizedPathWithDefault(locale, pathname, defaultLocale);
}

export function getLocalizedPathWithDefault(
  locale: string,
  pathname = "/",
  defaultLocale: AppLocale,
): string {
  const localeKey = resolveLocale(locale, defaultLocale);
  const normalizedPath = pathname === "" ? "/" : pathname;
  const strippedPath = stripLocalePrefix(normalizedPath);

  if (localeKey === defaultLocale) {
    return strippedPath;
  }

  return strippedPath === "/" ? `/${localeKey}` : `/${localeKey}${strippedPath}`;
}
