import { state, getCurrentUser } from '@/utils/store.uts'
import supa from '@/components/supadb/aksupainstance.uts'

/**
 * 将任意角色类型的原始值格式化为标准化的应用角色
 */
export function normalizeRole(rawRole: any | null): string {
  if (rawRole == null || rawRole === undefined) return 'unknown'
  const roleStr = String(rawRole).trim().toLowerCase()
  if (roleStr === 'admin') return 'admin'
  if (roleStr === 'merchant') return 'merchant'
  return 'unknown'
}

/**
 * 判断是否为纯后台管理员
 */
export function isAdminRole(role: string): boolean {
  return normalizeRole(role) === 'admin'
}

/**
 * 判断是否为商户角色
 */
export function isMerchantRole(role: string): boolean {
  return normalizeRole(role) === 'merchant'
}

/**
 * 获取当前的标准化角色 (同步方法)
 */
export function getCurrentAdminRole(): string {
  // 1. 最高优先级：当前响应式内存 userProfile（已查数据库）
  if (state.userProfile != null && state.userProfile!.role != null) {
    const memRole = normalizeRole(state.userProfile!.role)
    if (memRole === 'admin' || memRole === 'merchant') {
      return memRole
    }
  }

  // 2. Auth Session兜底获取（Tab 隔离）：
  const sessionUser = supa.getSession().user
  if (sessionUser != null) {
    const meta = sessionUser.get("user_metadata") as UTSJSONObject | null
    if (meta != null && meta.getString("role") != null) {
      const metaRole = normalizeRole(meta.getString("role"))
      if (metaRole === "admin" || metaRole === "merchant") return metaRole
    }
  }

  console.warn("[AdminRole] 未能获取到有效的管理端角色，准备安全降级...")
  return "unknown"
}

/**
 * 清理本地相关角色和管理端缓存 (登出时调用)
 */
export function clearAdminRoleCache(): void {
  // 清理 admin 专属
  uni.removeStorageSync('adminRole')
  uni.removeStorageSync('admin_role')
  uni.removeStorageSync('merchant_id')
}

/**
 * 校验并写入最新的 adminRole (用于 Login 后或者 Layout 挂载时强制刷新)
 */
export async function refreshAdminRole(): Promise<string> {
  const userStrProfile = await getCurrentUser()
  let finalRole = 'unknown'

  if (userStrProfile != null && userStrProfile.role != null) {
    finalRole = normalizeRole(userStrProfile.role)
    console.log('[AdminRole] 从 ak_users 读取真实身份成功:', finalRole)
  } else {
    // metadata fallback
    const sessionInfo = supa.getSession()
    if (sessionInfo.user != null) {
      const meta = sessionInfo.user?.get("user_metadata") as UTSJSONObject | null
      if (meta != null && meta.getString('role') != null) {
         finalRole = normalizeRole(meta.getString('role'))
         console.log('[AdminRole] 从 Auth Metadata 读取兜底身份:', finalRole)
      }
    }
  }

  if (finalRole !== 'unknown') {
    // uni.setStorageSync('adminRole', finalRole) // 移除缓存耦合，强制按单例会话状态刷新
    if (state.userProfile != null) {
        state.userProfile!.role = finalRole
    }
    console.log('[AdminRole] 最新角色已写入状态和缓存:', finalRole)
  }

  return finalRole
}

export function getVisibleTopMenuIds(role: string): string[] {
  const normRole = normalizeRole(role)
  if (normRole === 'admin') {
    return ['home', 'shop', 'user', 'order', 'product', 'marketing', 'distribution', 'kefu', 'finance', 'cms', 'decoration', 'app', 'setting', 'maintain']
  }

  if (normRole === 'merchant') {
    return ['home', 'shop', 'order', 'product', 'marketing', 'finance']
  }

  return ['home']
}

export function hasAdminModuleAccess(moduleId: string | undefined): boolean {   
  if (!moduleId) return true

  const role = getCurrentAdminRole()
  const normRole = normalizeRole(role)
  
  if (normRole === 'unknown') {
     return moduleId === 'home'
  }
  
  if (normRole === 'admin') {
    return true
  }

  if (normRole === 'merchant') {
    const allowed = ['home', 'shop', 'order', 'product', 'marketing', 'finance']
    return allowed.includes(moduleId)
  }

  return false
}
