import type { JSX } from 'react';
import { useCreation } from 'ahooks';

const roleList = ['owner', 'admin', 'member', 'guest'] as const;

export interface SessionPermissionProps {
  session: Record<string, any>;
  roles?: (typeof roleList)[number][];
  children: ((props: { hasPermission: boolean }) => JSX.Element | null) | JSX.Element;
}

export default function SessionPermission({ session, roles = ['owner', 'admin'], children }: SessionPermissionProps) {
  const hasPermission = useCreation(() => {
    return roles.includes(session?.user?.role || 'guest');
  }, [session?.user?.role, roles]);

  if (typeof children === 'function') {
    return children({ hasPermission });
  }

  if (hasPermission) {
    return children;
  }

  return null;
}
