import type { Authority, MenuNode } from '@/types/system'

export function flattenAuthorities(authorities: Authority[], depth = 0): Array<Authority & { depth: number }> {
  return authorities.flatMap((authority) => [
    { ...authority, depth },
    ...flattenAuthorities(authority.children || [], depth + 1),
  ])
}

export function flattenMenusForOptions(menus: MenuNode[], depth = 0): Array<MenuNode & { depth: number }> {
  return menus.flatMap((menu) => [
    { ...menu, depth },
    ...flattenMenusForOptions(menu.children || [], depth + 1),
  ])
}

export function collectCheckedLeafMenus(menus: MenuNode[], checkedKeys: Set<number>): MenuNode[] {
  return menus.flatMap((menu) => {
    const children = menu.children || []
    if (!children.length) {
      return checkedKeys.has(menu.ID) ? [menu] : []
    }

    return collectCheckedLeafMenus(children, checkedKeys)
  })
}
