"use client";

import { useAuth, type Role } from "@/lib/auth-context";
import { useEffect, type ReactNode } from "react";
import { useRouter } from "next/navigation";

type RouteGuardProps = {
  allowedRoles?: Role[];
  /** Jika status entity tidak sesuai, tampilkan read-only mode, bukan 403 */
  statusUnauthorized?: boolean;
  children: ReactNode;
};

export function RouteGuard({ allowedRoles, statusUnauthorized, children }: RouteGuardProps) {
  const { isAuthenticated, hasRole } = useAuth();
  const router = useRouter();
  const shouldRedirectLogin = !isAuthenticated;
  const isRoleAllowed = !allowedRoles || allowedRoles.length === 0 || (isAuthenticated && hasRole(...allowedRoles));
  const shouldRedirectForbidden = isAuthenticated && !!allowedRoles && allowedRoles.length > 0 && !isRoleAllowed && !statusUnauthorized;

  useEffect(() => {
    if (shouldRedirectLogin) {
      router.replace("/login");
      return;
    }

    if (shouldRedirectForbidden) {
      router.replace("/403");
    }
  }, [router, shouldRedirectForbidden, shouldRedirectLogin]);

  if (shouldRedirectLogin) {
    return null;
  }

  if (!isRoleAllowed && !statusUnauthorized) {
    return null;
  }

  return <>{children}</>;
}
