"use client";

import { ReactNode, useEffect } from "react";
import { useRouter } from "next/navigation";
import { UserRole } from "@/lib/types/user";
import { useAuthStore } from "@/lib/store/authStore";

export default function RequireRole({
  allowed,
  children,
}: {
  allowed: UserRole[];
  children: ReactNode;
}) {
  const router = useRouter();
  const user = useAuthStore((state) => state.user);

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

    if (!allowed.includes(user.role)) {
      router.replace("/");
    }
  }, [user, allowed, router]);

  if (!user || !allowed.includes(user.role)) {
    return null;
  }

  return <>{children}</>;
}
