import { describe, it, expect } from 'vitest'
import { hasPermission, isRouteAllowed, getAllowedMenuRoutes } from '@/utils/permission'
import type { RouteRecordNormalized } from 'vue-router'

function makeRoute(
  path: string,
  meta?: Record<string, unknown>,
  children?: RouteRecordNormalized[]
): RouteRecordNormalized {
  return {
    path,
    meta: meta ?? {},
    children: children ?? [],
    name: path,
    components: {},
    instances: {},
    aliasOf: undefined,
    leaveGuards: {} as any,
    updateGuards: {} as any,
    enterCallbacks: {},
    mods: new Set(),
    props: {},
    redirect: undefined,
    beforeEnter: undefined
  } as unknown as RouteRecordNormalized
}

describe('permission utils', () => {
  it('hasPermission returns true when no permission required', () => {
    expect(hasPermission(undefined, 'common_user')).toBe(true)
    expect(hasPermission([], 'common_user')).toBe(true)
  })

  it('hasPermission checks employee type', () => {
    expect(hasPermission(['flow_manager'], 'flow_manager')).toBe(true)
    expect(hasPermission(['flow_manager'], 'common_user')).toBe(false)
  })

  it('isRouteAllowed respects meta.permissions', () => {
    const allowed = makeRoute('/flow', { permissions: ['flow_manager'] })
    expect(isRouteAllowed(allowed, 'flow_manager')).toBe(true)
    expect(isRouteAllowed(allowed, 'common_user')).toBe(false)

    const publicRoute = makeRoute('/dashboard', {})
    expect(isRouteAllowed(publicRoute, 'common_user')).toBe(true)
  })

  it('getAllowedMenuRoutes filters by permissions', () => {
    const routes = [
      makeRoute('/', { title: '首页', icon: 'HomeFilled' }),
      makeRoute(
        '/system',
        { title: '系统管理', permissions: ['dept_manager'] },
        [makeRoute('/system/user', { title: '用户管理', permissions: ['dept_manager'] })]
      )
    ]
    const common = getAllowedMenuRoutes(routes, 'common_user')
    expect(common.some((r) => r.path === '/system')).toBe(false)

    const manager = getAllowedMenuRoutes(routes, 'dept_manager')
    expect(manager.some((r) => r.path === '/system')).toBe(true)
  })
})
