// 权限 Hook
// 依据：project_rules §3.1（前端禁止 role === "xxx" 硬编码，统一用 hasPermission）
// 从 localStorage 读取用户 permissions，提供 hasPermission 检查

import { useMemo } from "react";
import { getUser } from "@/lib/auth";
import type { Permission } from "@/lib/permissions";

export function usePermission() {
  const user = getUser();

  const permissions = useMemo(() => {
    return new Set(user?.permissions ?? []);
  }, [user]);

  function hasPermission(permission: Permission): boolean {
    return permissions.has(permission);
  }

  function hasAnyPermission(...required: Permission[]): boolean {
    return required.some((p) => permissions.has(p));
  }

  function hasAllPermissions(...required: Permission[]): boolean {
    return required.every((p) => permissions.has(p));
  }

  return {
    permissions: user?.permissions ?? [],
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    isAuthenticated: user !== null,
  };
}
