import { getButtonAuthorizeSelector } from '#/api/system/buttonAuthorize';

interface ButtonResource {
  children?: ButtonResource[];
  enCode?: string;
}

export function collectButtonCodes(resources: ButtonResource[]): Set<string> {
  const codes = new Set<string>();
  const pending = [...resources];
  while (pending.length) {
    const resource = pending.pop()!;
    if (resource.enCode) codes.add(resource.enCode);
    if (Array.isArray(resource.children)) pending.push(...resource.children);
  }
  return codes;
}

export async function getAssociatedButtonCodes(menuId: string): Promise<null | Set<string>> {
  try {
    const response = await getButtonAuthorizeSelector(menuId);
    const resources = response?.data?.list;
    return Array.isArray(resources) ? collectButtonCodes(resources) : null;
  } catch {
    return null;
  }
}

export function canShowButton(code: string, granted: boolean, associatedCodes: null | Set<string>): boolean {
  return granted || (associatedCodes !== null && !associatedCodes.has(code));
}
