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

export type AppLocale = (typeof routing.locales)[number];

export function resolveLocale(locale: string): AppLocale {
  if (locale === "en" || locale === "ar") {
    return locale;
  }

  return routing.defaultLocale;
}

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

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

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

  return pathname || "/";
}

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

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

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