import { cookies } from 'next/headers';

const SUPPORTED_LANGUAGES = ['en', 'ar'] as const;
type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];

/**
 * Get the dictionary (specific page) based on the language.
 * @param page - The page you want to fetch (e.g., 'home', 'about', etc.)
 * @returns The requested page of the dictionary.
 */
export const getDictionary = async (page: string) => {
  const cookieStore = await cookies();
  const language = cookieStore?.get('language')?.value as SupportedLanguage || 'en';

  if (!SUPPORTED_LANGUAGES.includes(language)) {
    throw new Error(`Language "${language}" not supported.`);
  }

  try {
    // Dynamically import the required language and page JSON
    const data = await import(`@/locale/${language}/${language}-${page}.json`);
    return data.default;
  } catch (error) {
    console.error(`Error loading dictionary for lang "${language}" and page "${page}":`, error);
    return {}; // Return empty object on error or missing file
  }
};
