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

export function middleware(request: NextRequest) {

  // قراءة التوكن
  const token =
    request.cookies.get("amtar_auth_token")?.value;

  // المسار الحالي
  const pathname = request.nextUrl.pathname;

  // جميع الصفحات المحمية
  const protectedRoutes = [
    "/search",
    "/search-map",
    "/find-agents",
    "/property-requests/add",
    "/services",
    "/listings",
    "/mortgage-calculator",
    "/advertising-license",
  ];

  // هل الصفحة محمية؟
  const isProtectedRoute =
    protectedRoutes.some((route) =>
      pathname.startsWith(route)
    );

  // إذا غير مسجل دخول
  if (isProtectedRoute && !token) {

    return NextResponse.redirect(
      new URL("/auth/signin", request.url)
    );
  }

  // السماح بالوصول
  return NextResponse.next();
}

export const config = {
  matcher: [
    "/search/:path*",
    "/search",
    "/search-map/:path*",
    "/find-agents/:path*",
    "/property-requests/add/:path*",
    "/services/:path*",
    "/listings/:path*",
    "/mortgage-calculator/:path*",
    "/advertising-license/:path*",
  ],
};