'use client';

import type { Permission } from '@pac/types';
import { useAuthStore } from '@/stores/auth-store';

/** module-level 常量 — 给 selector 返稳定空数组,避免 useSyncExternalStore 无限 loop 警告 */
const EMPTY_PERMS: readonly Permission[] = [];

/**
 * Reactive hook — returns true if the current user has every permission listed.
 * Reads from the in-memory auth store; recomputes on token change.
 *
 *   const canAssign = useHasPermission('plan:assign');
 *   const canBoth   = useHasPermission(['plan:assign', 'plan:recycle']);
 *
 * 注:user=null 时 selector 必须返**同一个引用**(否则 React 18+ 的 useSyncExternalStore
 * 检测到"snapshot 不稳",触发 "getServerSnapshot should be cached" 警告 + 死循环 re-render)。
 * 所以用 EMPTY_PERMS 常量,不写 `?? []`。
 */
export function useHasPermission(required: Permission | Permission[]): boolean {
  const perms = useAuthStore((s) => s.user?.permissions ?? EMPTY_PERMS);
  const list = Array.isArray(required) ? required : [required];
  if (list.length === 0) return true;
  const granted = new Set(perms);
  return list.every((p) => granted.has(p));
}
