import { USER_SCOPES } from '@/constants/entities/Scope';
import { lazyLoadView } from '@/utils/lazyloadview';
import { Scope, getScopes } from '@/utils/scopes';
import { RouteConfig } from 'vue-router';

interface ExpansionMenuProps {
  path: string;
  name: string;
  label: string;
  icon: string;
  order: string;
  children: RouteConfig[];
}

interface MenuItemProps {
  path: string;
  name: string;
  label: string;
  icon: string;
  order: string;
  scopes: Scope;
}

export function expansionMenuItem({
  path,
  name,
  label,
  icon,
  order,
  children,
}: ExpansionMenuProps): RouteConfig {
  const commonScopes = getScopesFromChildren(new Set<USER_SCOPES>(), children);
  const disabled =
    children.reduce((acc, r) => {
      r.meta?.disabled && acc.push(r.meta?.disabled);
      return acc;
    }, [] as boolean[]).length === children.length;
  return {
    component: async () => await lazyLoadView(import('@/recruits/layouts/main-view.vue')),
    path,
    name,
    meta: {
      label,
      icon,
      place: 'drawer',
      order,
      scopes: getScopes([...commonScopes]),
      disabled,
    },
    children,
  };
}

export function disabledMenuItem({
  path,
  name,
  label,
  icon,
  order,
  scopes,
}: MenuItemProps): RouteConfig {
  return {
    component: async () => await lazyLoadView(import('@/recruits/layouts/main-view.vue')),
    path,
    name,
    meta: {
      clickable: false,
      disabled: true,
      label,
      order,
      icon,
      place: 'drawer',
      scopes,
    },
  };
}

function getScopesFromChildren(
  commonScopes: Set<USER_SCOPES>,
  children: RouteConfig[]
): Set<USER_SCOPES> {
  for (const route of children) {
    const routeScopes: Scope = route.meta?.scopes;
    if (Array.isArray(routeScopes?.list)) {
      routeScopes.list.forEach((s) => commonScopes.add(s));
    }
    if (route.children) {
      getScopesFromChildren(commonScopes, route.children);
    }
  }

  return commonScopes;
}
