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

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

  const isAuthPage = pathname.startsWith("/dashboard/auth");
  const isProtectedPage = pathname.startsWith("/dashboard") && !isAuthPage;

  // user belum login, mau buka dashboard → redirect ke login
  if (!token && isProtectedPage) {
    return NextResponse.redirect(new URL("/dashboard/auth", request.url));
  }

  // user sudah login, tapi buka login → redirect ke dashboard
  if (token && isAuthPage) {
    return NextResponse.redirect(new URL("/dashboard/overview", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"],
};
