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';

  // Log to Sentry if we had to fallback, as it might indicate a routing issue
  if (!rawLocale || !supportedLocales.includes(rawLocale as string)) {
    console.warn(
      `[i18n] Invalid or missing requestLocale received: "${rawLocale}". Falling back to "en".`,
    );
  }

  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;
});
