import type { PermissionKey } from "@mrp/shared";
import { Navigate, Outlet } from "react-router-dom";

import { useAuth } from "../auth/AuthProvider";

export function ProtectedRoute({ requiredPermissions = [] }: { requiredPermissions?: PermissionKey[] }) {
  const { isReady, token, user } = useAuth();

  if (!isReady) {
    return <div className="p-10 text-center text-muted">Loading workspace...</div>;
  }

  if (!token || !user) {
    return <Navigate to="/login" replace />;
  }

  const permissionSet = new Set(user.permissions);
  const allowed = requiredPermissions.every((permission) => permissionSet.has(permission));

  return allowed ? <Outlet /> : <Navigate to="/" replace />;
}

