import { cookies } from "next/headers";

import { getDefaultAppLocale } from "@/lib/app-settings";
import { APP_LOCALE_COOKIE, getDictionary, normalizeLocale } from "@/lib/i18n";

export async function getCurrentLocale() {
  const cookieStore = await cookies();
  const cookieLocale = normalizeLocale(cookieStore.get(APP_LOCALE_COOKIE)?.value);

  if (cookieStore.get(APP_LOCALE_COOKIE)?.value) {
    return cookieLocale;
  }

  return getDefaultAppLocale();
}

export async function getPageCopy(
  pathname: string,
  fallbackTitle: string,
  fallbackDescription: string
) {
  const locale = await getCurrentLocale();
  const dict = getDictionary(locale);
  const copy = dict.pages[pathname as keyof typeof dict.pages];

  return {
    locale,
    dict,
    title: copy?.title ?? fallbackTitle,
    description: copy?.description ?? fallbackDescription
  };
}
