function pickText(payload = {}, keys = [], fallback = '') {
  for (const key of keys) {
    const value = String(payload?.[key] ?? '').trim()
    if (value) {
      return value
    }
  }
  return String(fallback || '').trim()
}

const PLATFORM_ADMIN_IDENTITIES = new Set(['admin', 'superadmin'])
const PLATFORM_ADMIN_ROLES = new Set(['admin', 'superadmin', '管理员', '系统管理员'])

function isTruthyAdminFlag(value) {
  if (value === true) {
    return true
  }

  if (typeof value === 'number') {
    return value === 1
  }

  return ['1', 'true', 'yes', 'on'].includes(String(value || '').trim().toLowerCase())
}

function normalizeRoleCodes(payload = {}) {
  const rawRoleCodes = Array.isArray(payload.roleCodes)
    ? payload.roleCodes
    : Array.isArray(payload.role_codes)
      ? payload.role_codes
      : typeof payload.roleCodes === 'string'
        ? payload.roleCodes.split(',')
        : []

  return rawRoleCodes.map((item) => String(item || '').trim()).filter(Boolean)
}

export function resolveAuthUserAdminFlag(payload = {}, roleCodes = []) {
  const username = String(payload?.username || payload?.account || '').trim().toLowerCase()
  const role = String(payload?.role || '').trim().toLowerCase()
  const normalizedRoleCodes = roleCodes.map((item) => String(item || '').trim().toLowerCase()).filter(Boolean)

  return (
    isTruthyAdminFlag(payload?.isAdmin)
    || isTruthyAdminFlag(payload?.is_admin)
    || PLATFORM_ADMIN_IDENTITIES.has(username)
    || PLATFORM_ADMIN_ROLES.has(role)
    || normalizedRoleCodes.some((item) => PLATFORM_ADMIN_IDENTITIES.has(item))
  )
}

export function normalizeAuthUserSnapshot(payload = {}, defaults = {}) {
  const username = pickText(payload, ['username', 'email', 'account'])
  const name = pickText(
    payload,
    ['name', 'userName', 'user_name', 'employeeName', 'employee_name'],
    username || defaults.defaultName
  )
  const department = pickText(payload, [
    'department',
    'departmentName',
    'department_name',
    'employeeDepartment',
    'employee_department'
  ])
  const position = pickText(payload, [
    'position',
    'employeePosition',
    'employee_position',
    'jobTitle',
    'job_title',
    'title'
  ])
  const employeeNo = pickText(payload, ['employeeNo', 'employee_no'])
  const costCenter = pickText(payload, ['costCenter', 'cost_center'])
  const financeOwnerName = pickText(payload, ['financeOwnerName', 'finance_owner_name'])
  const managerName = pickText(payload, [
    'managerName',
    'manager_name',
    'directManagerName',
    'direct_manager_name',
    'leaderName',
    'leader_name'
  ])
  const roleCodes = normalizeRoleCodes(payload)

  return {
    username,
    tenantId: pickText(payload, ['tenantId', 'tenant_id']),
    name,
    role: String(payload.role || defaults.defaultRole || ''),
    department,
    departmentName: department,
    position,
    grade: pickText(payload, ['grade', 'employeeGrade', 'employee_grade']),
    employeeNo,
    managerName,
    location: pickText(payload, ['location', 'employeeLocation', 'employee_location']),
    costCenter,
    financeOwnerName,
    riskProfile: payload.riskProfile && typeof payload.riskProfile === 'object' ? payload.riskProfile : {},
    roleCodes,
    email: pickText(payload, ['email'], username),
    avatar: pickText(payload, ['avatar'], name.slice(0, 1).toUpperCase()),
    isAdmin: resolveAuthUserAdminFlag(payload, roleCodes)
  }
}
