import Taro from '@tarojs/taro'

type StoredRole = { roleCode?: string; roleName?: string }
type StoredUser = {
  userId?: number
  roleCode?: string
  roleName?: string
  roles?: StoredRole[]
  isAdmin?: boolean | number | string
  isSuperAdmin?: boolean | number | string
}

const safeParseJSON = <T,>(v: any): T | null => {
  try {
    if (!v) return null
    if (typeof v === 'object') return v as T
    if (typeof v === 'string') return JSON.parse(v) as T
    return null
  } catch (_e) {
    return null
  }
}

export function getStoredUser(): StoredUser | null {
  try {
    const raw = Taro.getStorageSync('User')
    return safeParseJSON<StoredUser>(raw)
  } catch (_e) {
    return null
  }
}

export function hasRole(roleCode: string): boolean {
  const code = String(roleCode || '').trim()
  if (!code) return false

  const user = getStoredUser()
  if (!user) return false

  if (String(user.roleCode || '').trim() === code) return true
  if (Array.isArray(user.roles) && user.roles.some(r => String(r?.roleCode || '').trim() === code)) return true

  // Fallback: some backends only expose roleName; keep it permissive for common admin codes.
  const name = String(user.roleName || '').trim()
  if (code === 'superAdmin' && (user as any)?.isSuperAdmin) return true
  if (code === 'admin' && (user as any)?.isAdmin) return true
  if (name && name.toLowerCase().includes(code.toLowerCase())) return true

  return false
}

export function isAdmin(): boolean {
  const user = getStoredUser()
  const v: any = user?.isAdmin
  return v === true || v === 1 || v === '1'
}

export function isSuperAdmin(): boolean {
  const user = getStoredUser()
  const v: any = user?.isSuperAdmin
  return v === true || v === 1 || v === '1'
}

