import { NextResponse } from 'next/server';
import createIntlMiddleware from 'next-intl/middleware';
import { routing } from '@/i18n/routing';

const withLocale = (next) => {
  const intlMiddleware = createIntlMiddleware(routing);

  return async (request, event) => {
    const { pathname, search } = request.nextUrl;

    // Ignorer les ressources statiques et API routes
    if (
      pathname.startsWith('/_next') ||
      pathname.startsWith('/api') ||
      pathname.includes('.')
    ) {
      return next(request, event);
    }

    // Déterminer la locale
    let locale = 'fr';
    if (pathname.startsWith('/fr') || pathname.startsWith('/en')) {
      locale = pathname.split('/')[1];
    }

    // Si pas de locale dans l'URL, rediriger vers /fr
    if (!pathname.startsWith('/fr') && !pathname.startsWith('/en')) {
      return NextResponse.redirect(
        new URL(`/fr${pathname}${search}`, request.url)
      );
    }

    // Appliquer le middleware next-intl
    const response = await intlMiddleware(request, event);
    if (response) {
      // Ajouter la locale aux headers
      response.headers.set('x-locale', locale);
      return response;
    }

    const nextResponse = await next(request, event);
    // Ajouter la locale aux headers même pour les réponses suivantes
    nextResponse.headers.set('x-locale', locale);
    return nextResponse;
  };
};

export { withLocale };
