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

export function middleware(request: NextRequest) {
  const token = request.cookies.get("token")?.value;
  const { pathname } = request.nextUrl;

  const protectedRoutes = [
    "/profile",
    "/post-ad",
    "/payment",
    "/ad-details",
    "/orderHistory",
    "/orderStatus",
    "/wishlist",
    "/ongoing",
    "/increment",
    "/chat",
    "/searchList",
  ];

  const publicRoutes = ["/auth/login", "/auth/register"];

  const requiresAuth = protectedRoutes.some((route) =>
    pathname.startsWith(route)
  );
  // console.log("isLoginPage ----------");

  const isLoginPage = publicRoutes.some((route) => pathname.startsWith(route));
  // console.log("isLoginPage", isLoginPage);

  if (isLoginPage && token) {
    // return NextResponse.redirect(new URL("/", request.url));
  }

  if (requiresAuth && !token) {
    // return NextResponse.redirect(new URL("/auth/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/auth/login",
    "/auth/register",
    "/profile/:path*",
    "/post-ad",
    "/payment",
    "/ad-details",
    "/orderHistory",
    "/orderStatus/:path*",
    "/wishlist",
    "/ongoing/:path*",
    "/increment/:path*",
    "/chat",
    "/searchList",
    "/dashboard",
  ],
};
