import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const locales = ["ar", "en"] as const;
type Locale = (typeof locales)[number];

function getLocaleFromPath(pathname: string): Locale | null {
  for (const locale of locales) {
    if (pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`) {
      return locale;
    }
  }
  return null;
}

export function proxy(request: NextRequest) {
  const locale = getLocaleFromPath(request.nextUrl.pathname);
  if (!locale) return NextResponse.next();

  const response = NextResponse.next();
  response.cookies.set("web_locale", locale, { path: "/", sameSite: "lax" });
  return response;
}

export const config = {
  matcher: ["/ar/:path*", "/en/:path*"],
};
