import { NextResponse, type NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";

// Path yang boleh diakses oleh user yang login tapi belum accept Terms & Privacy.
const ALLOWED_WHEN_NOT_ACCEPTED = [
  "/accept-terms",
  "/terms",
  "/privacy",
];

export async function proxy(req: NextRequest) {
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
  if (!token) return NextResponse.next();
  if (token.acceptedTermsAndPrivacy) return NextResponse.next();

  const { pathname } = req.nextUrl;
  if (pathname.startsWith("/api/auth")) return NextResponse.next();
  if (
    ALLOWED_WHEN_NOT_ACCEPTED.some(
      (p) => pathname === p || pathname.startsWith(`${p}/`),
    )
  ) {
    return NextResponse.next();
  }

  const url = req.nextUrl.clone();
  url.pathname = "/accept-terms";
  url.search = "";
  return NextResponse.redirect(url);
}

export const config = {
  matcher: [
    // Lewati internal Next.js dan asset statis. Sisanya diperiksa proxy.
    "/((?!_next/static|_next/image|favicon.ico|images/|.*\\.(?:png|jpg|jpeg|svg|webp|ico|css|js|map|txt|xml)$).*)",
  ],
};
