import { useMemo } from 'react';
import { useGetMyProfileQuery } from './useCurrentProfile';

export interface PermissionSet {
  permissions: string[];
  /** True if the user holds any one of `required`. Empty `required` = allowed. */
  can: (required?: string[]) => boolean;
  /**
   * Whether the effective permission list has loaded. While false, `can()`
   * returns true so the shell does not flash an empty sidebar during the
   * first fetch; callers gating destructive actions should also check
   * `known` and disable rather than hide.
   */
  known: boolean;
}

/**
 * What the signed-in user is allowed to do.
 *
 * The list comes from `GET /profiles/me` (`permissions: string[]`), which the
 * API computes per session: role grants, portal account-type grants and
 * position grants combined. The access token itself carries no permission
 * claims, so nothing is decoded client-side any more.
 *
 * Fails open only while loading (`known: false`); once the server has
 * answered, `can()` is authoritative for show/hide. Enforcement remains
 * server-side — the worst a wrong answer here can do is offer a control that
 * then 403s.
 */
export function usePermissions(): PermissionSet {
  const { data, isSuccess } = useGetMyProfileQuery();

  return useMemo(() => {
    const permissions = data?.permissions ?? [];
    const known = isSuccess && Array.isArray(data?.permissions);
    const granted = new Set(permissions);

    return {
      permissions,
      known,
      can: (required?: string[]) => {
        if (!required?.length) return true;
        if (!known) return true;
        return required.some((permission) => granted.has(permission));
      },
    };
  }, [data?.permissions, isSuccess]);
}
