'use client';

import type { ReactNode } from 'react';
import { usePermissions } from '@/hooks/use-permissions';
import type { RolePermissions } from '@/lib/db/schema/users';

type Resource = keyof RolePermissions;
type Action<R extends Resource> = keyof RolePermissions[R];

interface PermissionGateProps<R extends Resource> {
  resource: R;
  action: Action<R>;
  children: ReactNode;
  fallback?: ReactNode;
}

export function PermissionGate<R extends Resource>({
  resource,
  action,
  children,
  fallback = null,
}: PermissionGateProps<R>) {
  const { can } = usePermissions();

  if (!can(resource, action)) {
    return <>{fallback}</>;
  }

  return <>{children}</>;
}
