import { getRequestConfig } from "next-intl/server";
import { cookies, headers } from "next/headers";

export const locales = ["en", "de", "fr"] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = "en";

export default getRequestConfig(async () => {
  // Try to get locale from cookie
  const cookieStore = await cookies();
  let locale = cookieStore.get("NEXT_LOCALE")?.value as Locale | undefined;

  // Fall back to Accept-Language header
  if (!locale || !locales.includes(locale)) {
    const headersList = await headers();
    const acceptLanguage = headersList.get("accept-language");
    if (acceptLanguage) {
      const preferredLocale = acceptLanguage
        .split(",")[0]
        ?.split("-")[0] as Locale;
      if (locales.includes(preferredLocale)) {
        locale = preferredLocale;
      }
    }
  }

  // Fall back to default
  if (!locale || !locales.includes(locale)) {
    locale = defaultLocale;
  }

  return {
    locale,
    messages: (await import(`../../public/locales/${locale}/common.json`)).default,
    onError(error) {
      if (error.code === "MISSING_MESSAGE") {
        console.warn(error.message);
      } else {
        console.error(error);
      }
    },
    getMessageFallback({ namespace, key }) {
      return key;
    },
  };
});
