'use client';

import { usePermissionsStore } from '@/stores/permissions-store';
import type { RolePermissions } from '@/lib/db/schema/users';

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

interface UsePermissionsReturn {
  can: <R extends Resource>(resource: R, action: Action<R>) => boolean;
  permissions: RolePermissions | null;
  isSuperAdmin: boolean;
  userId: string | null;
}

/**
 * Hook that provides a `can(resource, action)` check using the current user's
 * permissions from the permissions store (populated by PermissionsProvider).
 */
export function usePermissions(): UsePermissionsReturn {
  const permissions = usePermissionsStore((s) => s.permissions);
  const isSuperAdmin = usePermissionsStore((s) => s.isSuperAdmin);
  const userId = usePermissionsStore((s) => s.userId);

  function can<R extends Resource>(resource: R, action: Action<R>): boolean {
    // Super admins bypass all permission checks
    if (isSuperAdmin) return true;
    if (!permissions) return false;
    const resourcePerms = permissions[resource];
    if (!resourcePerms) return false;
    return !!(resourcePerms as Record<string, boolean>)[action as string];
  }

  return { can, permissions, isSuperAdmin, userId };
}
