import { useCallback, useEffect, useState } from 'react';
import { fetchMenuPermissions } from '../utils/backendApi';
import {
  type MenuPermissionsDto,
  type UserRole,
  canAccessMenu,
  normalizeRole,
} from '../utils/permissions';

let _cache: MenuPermissionsDto | null = null;
let _promise: Promise<MenuPermissionsDto> | null = null;

export function invalidateMenuPermissionsCache() {
  _cache = null;
  _promise = null;
}

function loadPermissions(): Promise<MenuPermissionsDto> {
  if (_cache) return Promise.resolve(_cache);
  if (_promise) return _promise;
  _promise = fetchMenuPermissions().then(data => {
    const normalized: MenuPermissionsDto = {
      role: normalizeRole(data.role),
      permissions: data.permissions ?? {},
    };
    _cache = normalized;
    _promise = null;
    return normalized;
  }).catch(err => {
    console.error('[useMenuPermissions] load failed', err);
    _promise = null;
    return { role: 'GUEST' as UserRole, permissions: { chart: true, settings: true } };
  });
  return _promise;
}

export function useMenuPermissions(sessionKey = 0) {
  const [data, setData] = useState<MenuPermissionsDto>(_cache ?? { role: 'GUEST', permissions: {} });
  const [loaded, setLoaded] = useState(_cache !== null);

  useEffect(() => {
    setLoaded(false);
    invalidateMenuPermissionsCache();
    loadPermissions().then(d => {
      setData(d);
      setLoaded(true);
    });
  }, [sessionKey]);

  const can = useCallback(
    (menuId: string) => canAccessMenu(data.permissions, menuId),
    [data.permissions],
  );

  return { role: data.role, permissions: data.permissions, isLoaded: loaded, can };
}
