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

type Lang = "ar" | "en";

function isSupported(lang: string | undefined): lang is Lang {
  return lang === "ar" || lang === "en";
}

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;

  // Ignore Next.js internals and static assets
  if (
    pathname.startsWith("/_next") ||
    pathname.startsWith("/api") ||
    pathname.startsWith("/favicon") ||
    pathname.startsWith("/robots.txt") ||
    pathname.startsWith("/sitemap") ||
    pathname.startsWith("/images") ||
    pathname.match(/\.(?:png|jpg|jpeg|webp|svg|gif|ico|txt|xml|map)$/)
  ) {
    return NextResponse.next();
  }

  const seg = pathname.split("/").filter(Boolean)[0];

  if (!seg) {
    const url = req.nextUrl.clone();
    url.pathname = "/ar";
    const res = NextResponse.redirect(url);
    res.cookies.set("lang", "ar", { path: "/" });
    return res;
  }

  if (!isSupported(seg)) {
    const url = req.nextUrl.clone();
    url.pathname = `/ar${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
    const res = NextResponse.redirect(url);
    res.cookies.set("lang", "ar", { path: "/" });
    return res;
  }

  const res = NextResponse.next();
  res.cookies.set("lang", seg, { path: "/" });
  return res;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image).*)"],
};

