import { getRequestConfig } from 'next-intl/server';
import * as Sentry from '@sentry/nextjs';

export default getRequestConfig(async ({ requestLocale }) => {
  // Hardened locale validation: only allow 'en' or 'de'
  // Use a temporary variable to validate before assigning to locale
  const rawLocale = await requestLocale;
  const supportedLocales = ['en', 'de'];
  const locale =
    typeof rawLocale === 'string' && supportedLocales.includes(rawLocale) ? rawLocale : 'en';

  // Silent fallback for missing locales to support internal requests (e.g. OG generation)
  if (!rawLocale || !supportedLocales.includes(rawLocale as string)) {
    // console.debug(`[i18n] Fallback to "en" for locale: "${rawLocale}"`);
  }

  return {
    locale,
    messages: (await import(`../messages/${locale}.json`)).default,
    onError(error) {
      if (error.code === 'MISSING_MESSAGE') {
        console.error(error.message);
      } else {
        console.error(error);
      }
      Sentry.captureException(error);
    },
    getMessageFallback({ namespace, key, error }) {
      const path = [namespace, key].filter((part) => part != null).join('.');
      if (error.code === 'MISSING_MESSAGE') {
        return path;
      }
      return 'fallback';
    },
  } as any;
});
