import { useCallback, useEffect, useState } from 'react';
import { PERMISSIONS_UPDATED_EVENT, readPermissions } from '../auth/permission-store';

export function usePermission() {
  const [permissions, setPermissions] = useState<string[]>(readPermissions);

  useEffect(() => {
    const refresh = () => setPermissions(readPermissions());
    window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
    window.addEventListener('storage', refresh);
    return () => {
      window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
      window.removeEventListener('storage', refresh);
    };
  }, []);

  const hasPermission = useCallback(
    (code: string): boolean => permissions.includes(code),
    [permissions],
  );
  const hasAnyPermission = useCallback(
    (...codes: string[]): boolean => codes.some((code) => permissions.includes(code)),
    [permissions],
  );
  const hasAllPermissions = useCallback(
    (...codes: string[]): boolean => codes.every((code) => permissions.includes(code)),
    [permissions],
  );

  return { permissions, hasPermission, hasAnyPermission, hasAllPermissions };
}
