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

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

  const protectedApiRoutes = [
    "/api/cart",
    "/api/wishlist",
    "/api/co-creation",
    "/api/checkout",
    "/api/coupon",
    "/api/user",
  ];

  const publicApiRoutes = [
    "/api/auth/login",
    "/api/auth/register",
    "/api/auth/logout",
    "/api/auth/[...nextauth]",
  ];

  if (pathname.startsWith("/api/")) {
    if (publicApiRoutes.some((route) => pathname.startsWith(route))) {
      return NextResponse.next();
    }

    if (protectedApiRoutes.some((route) => pathname.startsWith(route))) {
      if (!token) {
        return NextResponse.json(
          { success: false, message: "Unauthorized - Please login" },
          { status: 401 },
        );
      }
    }

    return NextResponse.next();
  }

  const protectedPages = [
    "/dashboard",
    "/profile",
    "/start-co-creation",
    "/customization",
    "/custom-design",
    "/project",
    "/order",
    "/bag",
  ];

  if (protectedPages.some((page) => pathname.startsWith(page))) {
    if (!token) {
      const loginUrl = new URL("/auth/login", request.url);
      loginUrl.searchParams.set("redirect", pathname + request.nextUrl.search);
      return NextResponse.redirect(loginUrl);
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/dashboard/:path*",
    "/profile/:path*",
    "/start-co-creation/:path*",
    "/customization/:path*",
    "/custom-design/:path*",
    "/order/:path*",
    "/bag",
    "/api/:path*",
  ],
};
