import { NextResponse, type NextRequest } from "next/server";
import { defaultLocale, isLocale, localeCookieName } from "@/lib/i18n/config";

function detectLocale(request: NextRequest) {
  const cookie = request.cookies.get(localeCookieName)?.value;
  if (isLocale(cookie)) return cookie;

  const header = request.headers.get("accept-language")?.toLowerCase() ?? "";
  if (header.startsWith("ar") || header.includes(",ar")) return "ar";
  if (header.startsWith("en") || header.includes(",en")) return "en";
  return defaultLocale;
}

export function middleware(request: NextRequest) {
  const { pathname, search } = request.nextUrl;

  if (
    pathname.startsWith("/api") ||
    pathname.startsWith("/admin") ||
    pathname.startsWith("/_next") ||
    pathname === "/robots.txt" ||
    pathname === "/sitemap.xml" ||
    pathname.includes(".")
  ) {
    return NextResponse.next();
  }

  const segments = pathname.split("/");
  const maybeLocale = segments[1];

  if (isLocale(maybeLocale)) {
    const response = NextResponse.next();
    if (request.cookies.get(localeCookieName)?.value !== maybeLocale) {
      response.cookies.set(localeCookieName, maybeLocale, {
        path: "/",
        maxAge: 60 * 60 * 24 * 365,
        sameSite: "lax",
      });
    }
    return response;
  }

  const locale = detectLocale(request);
  const url = request.nextUrl.clone();
  url.pathname = `/${locale}${pathname === "/" ? "" : pathname}`;
  url.search = search;
  return NextResponse.redirect(url);
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|images|uploads|.*\\.(?:svg|png|jpg|jpeg|webp|avif|ico|txt|xml)$).*)"],
};
