import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const path = request.nextUrl.pathname;
  console.log(path);
  const isPublicPath =
    path === "/productDetail" ||
    path === "/confirmAddress" ||
    path === "/sell" ||
    path === "/paymentCallback" ||
    path === "/buynow" ||
    path === "/product/edit" ||
    path === "/user/profile" ||
    path === "/confirmOrder" ||
    path === "/upload" ||
    path === "/myUpload" ||
    path === "/seller/signUp" ||
    path === "/deleteUser";
    

  const isAdminPath = path.includes("/admin");

  let isToken = false;
  let isAdminToken = false;
  const token = request.cookies.get("jazz_token")?.value || "";
  const admintoken = request.cookies.get("jazz_admin_token")?.value || "";
  if (token !== "" && token !== null) {
    isToken = true;
  }
  if (admintoken !== "" && admintoken !== null) {
    isAdminToken = true;
  }

  if (isAdminPath && !isAdminToken) {
    return NextResponse.redirect(new URL("/admin/login", request.nextUrl));
  }
  // console.log(isPublicPath,token)

  if (isPublicPath && !isToken) {
    return NextResponse.redirect(new URL("/auth/login", request.nextUrl));
  }

  // return request; // Return the original request if no conditions match
}

export const config = {
  matcher: [
    "/productDetail",
    "/confirmAddress",
    "/sell",
    "/buynow",
    "/paymentCallback",
    "/product/edit",
    "/user/profile",
    "/confirmOrder",
    "/upload",
    "/myUpload",
    "/seller/signUp",
    "/deleteUser",
    "/admin",
    "/admin/brand",
    "/admin/brand/addBrand",
    "/admin/category",
    "/admin/category/addCategory",
    "/admin/subCategory",
    "/admin/subCategory/addSubCategory",
    "/admin/attributes",
    "/admin/attributes/addAttributes",
    "/admin/variations",
    "/admin/variations/addVariation",
    "/admin/product",
    "/admin/product/addProduct",
    "/admin/recommended&featured",
    "/admin/seller",
    "/admin/seller/addSeller",
    "/admin/user",
    "/admin/user/addUser",
  ],
};
