import { UserInfo } from './api'

export function isAuthenticated(): boolean {
  try {
    return !!localStorage.getItem('access_token')
  } catch {
    return false
  }
}

export function getStoredUser(): UserInfo | null {
  try {
    const raw = localStorage.getItem('user')
    return raw ? (JSON.parse(raw) as UserInfo) : null
  } catch {
    return null
  }
}

export function setStoredUser(user: UserInfo | null) {
  if (user) {
    localStorage.setItem('user', JSON.stringify(user))
  } else {
    localStorage.removeItem('user')
  }
}

export function clearAuth() {
  localStorage.removeItem('access_token')
  localStorage.removeItem('user')
}

export type RoleName = 'system_admin' | 'admin' | 'user'

const ROLE_RANK: Record<RoleName, number> = {
  system_admin: 3,
  admin: 2,
  user: 1,
}

export function roleRank(role: RoleName): number {
  return ROLE_RANK[role] ?? 0
}

export function roleLabel(role: RoleName): string {
  switch (role) {
    case 'system_admin':
      return '系统管理员'
    case 'admin':
      return '管理员'
    case 'user':
      return '用户'
  }
}

export function canAccess(role: RoleName, allowed: RoleName[]): boolean {
  return allowed.includes(role)
}

export function canManageUsers(role: RoleName): boolean {
  return role === 'admin' || role === 'system_admin'
}

export function canDeleteUsers(role: RoleName): boolean {
  return role === 'system_admin'
}
