import type { RouteRecordNormalized, RouteRecordRaw, RouteLocationNormalized } from 'vue-router'

export type EmployeeType = 'common_user' | 'dept_manager' | 'flow_manager' | 'super_admin'

export function hasPermission(required: EmployeeType[] | undefined, employeeType?: string): boolean {
  if (!required || required.length === 0) return true
  return required.includes(employeeType as EmployeeType)
}

export function isRouteAllowed(
  route: RouteRecordRaw | RouteRecordNormalized | RouteLocationNormalized,
  employeeType?: string
): boolean {
  const permissions = route.meta?.permissions as EmployeeType[] | undefined
  return hasPermission(permissions, employeeType)
}

export function isRoutePathAllowed(to: { matched: readonly RouteRecordNormalized[] }, employeeType?: string): boolean {
  return to.matched.every((route) => isRouteAllowed(route, employeeType))
}

export interface MenuRoute {
  path: string
  meta: RouteRecordNormalized['meta']
  children: RouteRecordRaw[]
}

export function getAllowedMenuRoutes(routes: RouteRecordNormalized[], employeeType?: string): MenuRoute[] {
  return routes
    .filter((r) => r.path !== '/login' && r.meta?.hidden !== true)
    .filter((r) => r.children && r.children.length > 0)
    .map((r) => ({
      path: r.path,
      meta: r.meta,
      children: r.children!.filter((c) => c.meta?.hidden !== true && isRouteAllowed(c, employeeType)),
    }))
    .filter((r) => isRouteAllowed({ meta: r.meta } as RouteRecordRaw, employeeType) || r.children.length > 0)
}
