import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

let locales = ["tr", "en"];
let defaultLocale = "tr";

// Get the preferred locale
function getLocale(request: NextRequest): string {
  const headers = new Headers(request.headers);
  const acceptLanguage = headers.get("accept-language");
  
  if (!acceptLanguage) return defaultLocale;

  const negotiatorHeaders: Record<string, string> = {};
  headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  try {
    const languages = new Negotiator({ headers: negotiatorHeaders }).languages();
    return match(languages, locales, defaultLocale);
  } catch (e) {
    return defaultLocale;
  }
}

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  
  // Skip public files and internal next paths
  if (
    pathname.startsWith('/_next') ||
    pathname.startsWith('/api') ||
    pathname.includes('.')
  ) {
    return;
  }

  // Handle Admin Panel Authentication & Routing Bypass
  if (pathname.startsWith('/admin')) {
    // Exclude /admin/login from the check
    if (pathname === '/admin/login') {
      return;
    }

    // Check for admin session
    const session = request.cookies.get('admin_session');
    if (!session || session.value !== 'true') {
      request.nextUrl.pathname = '/admin/login';
      return NextResponse.redirect(request.nextUrl);
    }
    
    // Allow authenticated admin traffic
    return;
  }

  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) return;

  // Redirect if there is no locale
  const locale = getLocale(request);
  request.nextUrl.pathname = `/${locale}${pathname}`;
  
  return NextResponse.redirect(request.nextUrl);
}

export const config = {
  matcher: [
    // Skip all internal paths (_next, static files, api)
    '/((?!_next|api|favicon.ico|.*\\..*).*)',
  ],
};
