import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getCountryByDomain, supportedLocales } from './lib/countries';
import { 
  getAuthUser, 
  isProtectedClientRoute, 
  isProtectedFreelancerRoute, 
  getRedirectUrl 
} from './lib/auth-middleware';

export async function middleware(request: NextRequest) {
  const { pathname, hostname } = request.nextUrl;
  
  console.log('🚀 Middleware triggered for:', pathname);
  
  // Skip middleware for static files and API routes
  if (
    pathname.startsWith('/_next') ||
    pathname.startsWith('/api') ||
    pathname.startsWith('/assets') ||
    pathname.includes('.')
  ) {
    console.log('⏭️ Skipping middleware for:', pathname);
    return NextResponse.next();
  }

  // Get country configuration based on domain
  // For localhost development, use a default config with 'en' as default language
  let country = getCountryByDomain(hostname);
  
  if (!country && (hostname === 'localhost' || hostname.includes('localhost'))) {
    // Default config for development with 'en' as default
    country = {
      id: 'localhost',
      name: 'Development',
      code: 'US',
      domain: 'localhost:3000',
      languages: ['en', 'fr', 'de', 'it', 'pt', 'es'],
      defaultLanguage: 'en',
      currency: 'USD',
      currencySymbol: '$',
      packagePrice: 9.90,
      paymentGateways: ['stripe']
    };
  } else if (!country) {
    country = getCountryByDomain('smile24.ch'); // Fallback to Switzerland
  }
  
  // If no country found, use default
  if (!country) {
    return NextResponse.next();
  }
  
  // Check if the pathname includes a locale
  const pathnameHasLocale = supportedLocales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) {
    // Extract locale from pathname
    const locale = pathname.split('/')[1];
    
    // Check if locale is supported by the country
    if (!country.languages.includes(locale)) {
      // Redirect to default language for this country
      const newUrl = new URL(request.url);
      newUrl.pathname = pathname.replace(`/${locale}`, `/${country.defaultLanguage}`);
      return NextResponse.redirect(newUrl);
    }
    
    // Temporarily disable middleware role checking to test client-side protection
    // The layouts will handle the role-based protection instead
    if (isProtectedClientRoute(pathname) || isProtectedFreelancerRoute(pathname)) {
      console.log('🔒 Protected route detected (skipping middleware check):', pathname);
      // Let the layout components handle the protection for now
    }
    
    // Add country info to headers
    const response = NextResponse.next();
    response.headers.set('x-country-code', country.code);
    response.headers.set('x-country-domain', country.domain);
    return response;
  }

  // No locale in pathname, redirect to default locale
  const newUrl = new URL(request.url);
  newUrl.pathname = `/${country.defaultLanguage}${pathname}`;
  return NextResponse.redirect(newUrl);
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - assets (public assets)
     */
    '/((?!api|_next/static|_next/image|favicon.ico|assets).*)',
  ],
};
