import type { MenuItem, LoginResponse, UserInfoResponse, RoutesResponse } from '@/types/menu'

// ────────── 模拟用户数据库 ──────────
const mockUsers = {
  admin: { token: 'mock-token-admin', roles: ['admin'], name: '超级管理员', avatar: '' },
  editor: { token: 'mock-token-editor', roles: ['editor'], name: '内容编辑', avatar: '' }
}

// Token 反查用户
const tokenMap: Record<string, typeof mockUsers.admin> = {
  'mock-token-admin': mockUsers.admin,
  'mock-token-editor': mockUsers.editor
}

// ────────── 模拟后端存储的全量路由 ──────────
// 真实场景中这份数据存在数据库，后端根据角色过滤后返回
const allAsyncRoutes: MenuItem[] = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: 'dashboard/index',
    meta: { title: '首页', icon: 'HomeFilled', roles: ['admin', 'editor'] }
  },
  {
    path: "/sdk",
    name: "Sdk",
    component: "sdk/index",
    meta: { title: "SDK管理", icon: "Box", roles: ["admin"] },
    children: [
      {
        path: "detail",
        name: "SdkDetail",
        component: 'sdk/detail',
        meta: { title: "管理详情", icon: "Box", roles: ["admin"], hidden: true },
      }
    ]
  },
  {
    path: '/system',
    name: 'System',
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
    children: [
      {
        path: 'user',
        name: 'SystemUser',
        component: 'system/user/index',
        meta: { title: '用户管理', icon: 'User', roles: ['admin'] }
      },
      {
        path: 'role',
        name: 'SystemRole',
        component: 'system/role/index',
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin'] }
      }
    ]
  },
  {
    path: '/content',
    name: 'Content',
    redirect: '/content/article',
    meta: { title: '内容管理', icon: 'Document', roles: ['admin', 'editor'] },
    children: [
      {
        path: 'article',
        name: 'Article',
        component: 'content/article/index',
        meta: { title: '文章管理', icon: 'Document', roles: ['admin', 'editor'] }
      }
    ]
  }
]

// ────────── 工具函数 ──────────
function filterRoutesByRoles(routes: MenuItem[], roles: string[]): MenuItem[] {
  return routes.reduce<MenuItem[]>((acc, route) => {
    const allowed = route.meta?.roles
    const hasPermission = !allowed || roles.some(r => allowed.includes(r))
    if (hasPermission) {
      const item = { ...route }
      if (item.children?.length) {
        item.children = filterRoutesByRoles(item.children, roles)
      }
      acc.push(item)
    }
    return acc
  }, [])
}

const delay = (ms: number) => new Promise(r => setTimeout(r, ms))

// ────────── Mock 接口 ──────────
/** 模拟登录 */
export async function mockLogin(username: string, password: string): Promise<LoginResponse> {
  await delay(500)
  const user = mockUsers[username as keyof typeof mockUsers]
  if (user && password === '123456') {
    return { code: 200, data: { token: user.token } }
  }
  throw new Error('用户名或密码错误')
}

/** 模拟获取用户信息 */
export async function mockGetUserInfo(token: string): Promise<UserInfoResponse> {
  await delay(200)
  const user = tokenMap[token]
  if (!user) throw new Error('Token 无效或已过期')
  return { code: 200, data: { name: user.name, roles: user.roles, avatar: user.avatar } }
}

/** 模拟获取权限路由（后端根据角色过滤后返回） */
export async function mockGetRoutes(token: string): Promise<RoutesResponse> {
  await delay(300)
  const user = tokenMap[token]
  if (!user) throw new Error('Token 无效或已过期')
  // 深拷贝，避免修改原始数据
  const routes = filterRoutesByRoles(JSON.parse(JSON.stringify(allAsyncRoutes)), user.roles)
  return { code: 200, data: routes }
}
