// middlewares/withUser.ts
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";

export const withUser = (next: any) => {
  return async (request: NextRequest, _next: NextFetchEvent) => {
    const pathname = request.nextUrl.pathname;

    const protectedPaths = [
      "/account",
      "/checkout",
      "/subscribe",
      "/statistics",
      "/received-orders",
      "/my-products",
      "/messages",
      "/returns",
    ];

    const onlyVendorPaths = [
      "/subscribe",
      "/statistics",
      "/received-orders",
      "/my-products",
      "/messages",
      "/returns",
      "/account/subscriptions",
    ]

    // Check if the request is to a protected path
    const isProtected = protectedPaths.some((path) => pathname.startsWith(path));

    if (isProtected) {
      const userId = request.cookies.get("user_token")?.value;
      const userType = request.cookies.get("user_type")?.value;

      if (!userId) {
        return NextResponse.redirect(new URL("/", request.url));
      }

      if (userType !== "vendor") {
        if (onlyVendorPaths.some((path)=> pathname.startsWith(path)) ) {
            return NextResponse.redirect(new URL("/", request.url));
        }
      }
    }

    return next(request, _next);
  };
};
