import { getRequestConfig } from 'next-intl/server';
import { headers } from 'next/headers';

export const locales = ['en', 'zh'] as const;
export const defaultLocale = 'en' as const;

export type Locale = (typeof locales)[number];

async function getLocaleFromHeaders(): Promise<Locale> {
  const headersList = await headers();
  const acceptLanguage = headersList.get('accept-language');
  
  if (acceptLanguage) {
    // Parse accept-language header
    const languages = acceptLanguage
      .split(',')
      .map(lang => lang.split(';')[0].trim().toLowerCase());
    
    // Check for exact matches first
    for (const lang of languages) {
      if (locales.includes(lang as Locale)) {
        return lang as Locale;
      }
    }
    
    // Check for language prefix matches (e.g., 'zh-CN' -> 'zh')
    for (const lang of languages) {
      const prefix = lang.split('-')[0];
      if (locales.includes(prefix as Locale)) {
        return prefix as Locale;
      }
    }
  }
  
  return defaultLocale;
}

export default getRequestConfig(async () => {
  // Get locale from user preference (cookie) or browser headers
  const headersList = await headers();
  const cookieHeader = headersList.get('cookie');
  
  let locale: Locale = defaultLocale;
  
  // Parse locale from cookies first (user preference takes priority)
  if (cookieHeader) {
    const cookies = cookieHeader.split(';');
    const localeCookie = cookies.find(cookie => cookie.trim().startsWith('locale='));
    if (localeCookie) {
      const localeValue = localeCookie.split('=')[1]?.trim();
      if (localeValue && locales.includes(localeValue as Locale)) {
        locale = localeValue as Locale;
      }
    }
  }
  
  // Only detect from headers if no valid cookie found
  if (!cookieHeader || !cookieHeader.includes('locale=')) {
    locale = await getLocaleFromHeaders();
  }

  return {
    locale,
    messages: (await import(`../../messages/${locale}.json`)).default
  };
});