import { useQuery } from '@tanstack/react-query';
import { menuApi, MenuResp } from '@/api/menu';
import { useMemo } from 'react';

export interface MenuPermissions {
  canRead: boolean;
  canCreate: boolean;
  canUpdate: boolean;
  canDelete: boolean;
  canApprove: boolean;
  canExport: boolean;
  canExecute: boolean;
}

/**
 * menuCode 별 사용자 권한 보유 여부.
 * 메뉴 트리에서 해당 menuCode 의 permissions 배열을 평탄화하여 boolean 으로 반환.
 */
export function usePermission(menuCode: string): MenuPermissions {
  const { data: tree = [] } = useQuery({
    queryKey: ['menu', 'my'],
    queryFn: menuApi.myMenus,
    staleTime: 5 * 60 * 1000,
  });

  return useMemo(() => {
    const perms = findPermissions(tree, menuCode);
    return {
      canRead:    perms.includes('READ'),
      canCreate:  perms.includes('CREATE'),
      canUpdate:  perms.includes('UPDATE'),
      canDelete:  perms.includes('DELETE'),
      canApprove: perms.includes('APPROVE'),
      canExport:  perms.includes('EXPORT'),
      canExecute: perms.includes('EXECUTE'),
    };
  }, [tree, menuCode]);
}

function findPermissions(nodes: MenuResp[], code: string): string[] {
  for (const n of nodes) {
    if (n.menuCode === code) return n.permissions ?? [];
    const found = findPermissions(n.children ?? [], code);
    if (found.length) return found;
  }
  return [];
}
