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

export function isExternalMenu(menu: Pick<MenuNode, 'path' | 'component'>) {
  return (
    menu.path.startsWith('http://') ||
    menu.path.startsWith('https://') ||
    menu.component.startsWith('http://') ||
    menu.component === '/'
  )
}

function normalizePathSegment(path: string) {
  if (!path) {
    return ''
  }

  return path.replace(/^\/+/, '').replace(/\/+$/, '')
}

export function buildFullMenus(
  menus: MenuNode[],
  parentPath = '',
  parentName?: string,
): AppMenu[] {
  return [...menus]
    .sort((left, right) => left.sort - right.sort)
    .map((menu) => {
      const normalized = normalizePathSegment(menu.path)
      const fullPath = isExternalMenu(menu)
        ? menu.path
        : `${parentPath}/${normalized}`.replace(/\/+/g, '/')

      const children = buildFullMenus(menu.children || [], fullPath, menu.name)

      return {
        ...menu,
        parentName,
        fullPath,
        fullPathKey: fullPath.replace(/^\//, ''),
        children,
      }
    })
}

export function flattenMenus(menus: AppMenu[]): AppMenu[] {
  return menus.flatMap((menu) => [menu, ...flattenMenus(menu.children || [])])
}

export function findDefaultRoute(menus: AppMenu[], routeName?: string) {
  const flatMenus = flattenMenus(menus).filter((menu) => !isExternalMenu(menu))
  const byDefaultName = flatMenus.find((menu) => menu.name === routeName)
  if (byDefaultName) {
    return byDefaultName.fullPath
  }

  return flatMenus[0]?.fullPath
}
