
import type { SidebarItem } from '~/types/menuAkses/sidebar'
import type { PageAccess } from '~/types/menuAkses/access'
interface SidebarItemWithPermissions extends SidebarItem {
  permissions: string[];
}

export function mergeSidebar(menuItems: SidebarItem[], allowedPages: PageAccess[]): SidebarItem[] {
  const result: SidebarItem[] = []

  for (const item of menuItems) {
    // Jika punya anak (children)
    //console.log('item', item);
    //console.log('allowedPages', allowedPages);
    if (Array.isArray(item.children)) {
      const filteredChildren = mergeSidebar(item.children, allowedPages)
       //console.log('ada array item', item);
       
      // console.log('filteredChildren', filteredChildren);
      if (filteredChildren.length > 0) {
        result.push({
          ...item,
          children: filteredChildren
        })
      }
      //console.log('result', result);
    }

    // Jika punya path, cocokkan dengan json dummy / backend
    else if (item.to) {
      const matchPage = allowedPages.find(page => page.title === item.title && page.path === item.to) //cocokkan title dan path link halaman

      //console.log('match', matchPage,matchPage?.permissions);
      if (matchPage && matchPage.permissions?.includes('view')) { 
        result.push({
          ...item,
          permissions: matchPage?.permissions,
          
        } as SidebarItemWithPermissions)
      }
    }
  }

  return result
}

export function mergeSidebarIcon(staticIcon: any[], IconAccess: any[]) {
  const result : any[] = []

  for (const item of staticIcon) {
    const matchIcon = IconAccess.find(icon => icon.id === item.id)
    //console.log('matchIcon', matchIcon);
    if (matchIcon) {
      result.push({
          ...item,
          
      })
    }

  }

  return result
}

