import { type AppLocale, defaultLocale, isAppLocale } from '@/config/i18n';
import { routing } from '@/i18n/routing';

export async function getCurrentLocale(): Promise<AppLocale> {
  // On the client we cannot use next/headers; fall back to default.
  if (typeof window !== 'undefined') {
    return defaultLocale;
  }

  try {
    // Dynamic import keeps next/headers server-only.
    const { cookies } = await import('next/headers');
    const cookieStore = await cookies();
    const localeCookie = cookieStore.get('NEXT_LOCALE')?.value;

    if (localeCookie && isAppLocale(localeCookie) && routing.locales.includes(localeCookie)) {
      return localeCookie;
    }

    return defaultLocale;
  } catch {
    return defaultLocale;
  }
}
