import { FC } from 'react';
import { Navigate } from 'react-router-dom';

import { useAuth } from 'src/contexts/JWTContext';
import {
  hasAnyPermissions,
  hasAllPermissions,
  UserPermissions,
} from 'src/utils/permissions';

export type PermissionsGuardProps = {
  requiredPermissions: UserPermissions[];
  strict?: boolean;
};

const PermissionsGuard: FC<
  React.PropsWithChildren<PermissionsGuardProps>
> = props => {
  const { children, requiredPermissions, strict = false } = props;

  const { permissions } = useAuth();

  if (strict && !hasAllPermissions(permissions, requiredPermissions)) {
    return <Navigate to="/" />;
  }

  if (!strict && !hasAnyPermissions(permissions, requiredPermissions)) {
    return <Navigate to="/" />;
  }

  return <>{children}</>;
};

export default PermissionsGuard;
