"use server";
import { NextResponse } from "next/server";

// Define protected and auth paths
const userProtectedPaths = [
  "/user",
  "/print",
  "/order-details",
  "/alert",
  "/payment",
  "/wishlist",
];

const vendorPaths = [
  "/vendor",
  "/user/withdrawing",
  "/user/reports",
  "/sign-in-vendor",
  "/sign-up-vendor",
  "/sign-up-affiliate",
  "/sign-in-affiliate",
  "/affiliate",
];

const publicPaths = ["/sign-in", "/sign-up", "/forgot-password", "/verify-otp"];

export function middleware(req) {
  const { pathname } = req.nextUrl;
  const isLoggedIn = !!req.cookies.get("token")?.value;

  const isVendorPath = vendorPaths.some((path) => pathname == path);

  const isProtectedPath = userProtectedPaths.some((path) =>
    pathname.startsWith(path)
  );

  const isPublicPath = publicPaths.some((path) => pathname.startsWith(path));

  if (isVendorPath) {
    return NextResponse.redirect(new URL("/not-found", req.url));
  }

  if (isPublicPath) {
    if (isLoggedIn) {
      return NextResponse.redirect(new URL("/user", req.url));
    }
    return NextResponse.next();
  }

  // Early return for public paths to avoid unnecessary checks
  if (isPublicPath) {
    if (isLoggedIn) {
      return NextResponse.redirect(new URL("/user", req.url));
    }
    return NextResponse.next();
  }

  // Perform async checks only for paths that need them
  if (isProtectedPath) {
    // Protect protected routes
    if (isProtectedPath && !isLoggedIn) {
      return NextResponse.redirect(new URL("/sign-in", req.url));
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: [
    "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};
