import { ReactNode } from "react";
import { useAuth } from "../context/AuthContext";

interface WithRolesProps {
  roles: string[]; // e.g., ["admin", "super_admin"]
  fallback?: ReactNode;
  children: ReactNode;
}

interface WithUserTypeProps {
  required: string; // e.g., ["admin", "super_admin"]
  fallback?: ReactNode;
  children: ReactNode;
}
export const useHasRole = (requiredRoles: string[]) => {
  const { user } = useAuth();
  const currentRoles = user?.roles?.map((r) => r.key) || [];

  return requiredRoles.some((role) => currentRoles.includes(role));
};

export const WithRoles = ({
  roles,
  fallback = null,
  children,
}: WithRolesProps) => {
  return useHasRole(roles) ? children : fallback;
};


export const useIsExternal = (required:string)=>{
  const { user } = useAuth();
  const currentUserType  = user?.userType || ""
  return required === currentUserType
}

export const WithExternalUserType = ({
  required,
  fallback = null,
  children,
}:WithUserTypeProps)=>{
  return useIsExternal(required) ? children : fallback
}