/**
 * 数据验证工具
 * 用于确保 API 响应数据的一致性和安全性
 */

/**
 * 验证并确保数据是数组
 * @param {any} data - 需要验证的数据
 * @param {string} context - 上下文信息，用于日志记录
 * @returns {Array} 确保返回数组
 */
export const ensureArray = (data, context = 'unknown') => {
  if (Array.isArray(data)) {
    return data
  }
  
  console.warn(`[DataValidator] ${context}: 期望数组但收到`, typeof data, data)
  return []
}

/**
 * 验证 API 响应格式
 * @param {Object} response - API 响应对象
 * @param {string} context - 上下文信息
 * @returns {Object} 标准化的响应对象
 */
export const validateApiResponse = (response, context = 'API') => {
  if (!response) {
    console.warn(`[DataValidator] ${context}: 响应为空`)
    return { data: [], pagination: null }
  }

  // 检查响应是否有 data 字段
  if (!response.hasOwnProperty('data')) {
    console.warn(`[DataValidator] ${context}: 响应缺少 data 字段`, response)
    return { data: [], pagination: null }
  }

  return {
    data: response.data,
    pagination: response.pagination || null,
    message: response.message || '',
    code: response.code || 200
  }
}

/**
 * 验证并处理列表数据
 * @param {Object} response - API 响应
 * @param {string} context - 上下文信息
 * @returns {Object} 包含验证后的数据和分页信息
 */
export const validateListResponse = (response, context = 'List API') => {
  const validatedResponse = validateApiResponse(response, context)
  
  return {
    data: ensureArray(validatedResponse.data, context),
    pagination: validatedResponse.pagination,
    message: validatedResponse.message,
    code: validatedResponse.code
  }
}

/**
 * 验证分页信息
 * @param {Object} pagination - 分页对象
 * @returns {Object} 标准化的分页对象
 */
export const validatePagination = (pagination) => {
  if (!pagination || typeof pagination !== 'object') {
    return {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    }
  }

  return {
    page: parseInt(pagination.page) || 1,
    limit: parseInt(pagination.limit) || 10,
    total: parseInt(pagination.total) || 0,
    totalPages: parseInt(pagination.totalPages) || 0
  }
}

/**
 * 安全的数据访问器
 * @param {Object} obj - 对象
 * @param {string} path - 属性路径，如 'data.list'
 * @param {any} defaultValue - 默认值
 * @returns {any} 安全访问的值
 */
export const safeGet = (obj, path, defaultValue = null) => {
  try {
    const keys = path.split('.')
    let result = obj
    
    for (const key of keys) {
      if (result === null || result === undefined) {
        return defaultValue
      }
      result = result[key]
    }
    
    return result !== undefined ? result : defaultValue
  } catch (error) {
    console.warn(`[DataValidator] safeGet 访问路径 "${path}" 失败:`, error)
    return defaultValue
  }
}

export default {
  ensureArray,
  validateApiResponse,
  validateListResponse,
  validatePagination,
  safeGet
}