/**
 * Mock 工具函数
 */

/**
 * 生成随机 Token
 * @returns {string}
 */
export const generateToken = () => {
  return 'Bearer mock_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

/**
 * 模拟延迟
 * @param {number} ms 延迟毫秒数
 * @returns {Promise}
 */
export const delay = (ms = 200) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

/**
 * 验证请求参数
 * @param {Object} data 请求数据
 * @param {Array} requiredFields 必填字段
 * @returns {Object|null} 错误信息或 null
 */
export const validateRequired = (data, requiredFields) => {
  for (const field of requiredFields) {
    if (!data[field] || data[field].toString().trim() === '') {
      return {
        error: 1,
        msg: `${field} 不能为空`,
        data: null,
      };
    }
  }
  return null;
};

/**
 * 验证密码长度
 * @param {string} password 密码
 * @param {number} min 最小长度
 * @param {number} max 最大长度
 * @returns {Object|null} 错误信息或 null
 */
export const validatePasswordLength = (password, min = 6, max = 16) => {
  if (password.length < min || password.length > max) {
    return {
      error: 1,
      msg: `密码长度必须在 ${min}-${max} 位`,
      data: null,
    };
  }
  return null;
};

/**
 * 创建成功响应
 * @param {*} data 响应数据
 * @param {string} msg 响应消息
 * @returns {Object}
 */
export const createSuccessResponse = (data = null, msg = '操作成功') => {
  return {
    error: 0,
    msg,
    data,
  };
};

/**
 * 创建错误响应
 * @param {string} msg 错误消息
 * @param {number} error 错误码
 * @param {*} data 响应数据
 * @returns {Object}
 */
export const createErrorResponse = (msg, code = 1, data = null) => {
  return {
    code,
    msg,
    data,
  };
};

/**
 * 从请求头中提取 Token
 * @param {Request} request 请求对象
 * @returns {string|null}
 */
export const extractToken = (request) => {
  const authorization = `Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoiYWRtaW4iLCJ1aWQiOjEsImF1ZCI6IiIsImV4cCI6MTc1MTk0NDQ3MiwiaWF0IjoxNzUxODU4MDcyLCJpc3MiOiIiLCJqdGkiOiI2YTIxMzk4NzYzOTliYzY5NTViY2Y5ZTcxOGQ5ODZjYyIsIm5iZiI6MTc1MTg1ODA3Miwic3ViIjoiIn0.-1wdpM_1uZq33YpaDUamtF-MY4c5FhZOItMp5CUTPvg`;
  if (authorization && authorization.startsWith('Bearer ')) {
    return authorization.substring(7);
  }
  return null;
};

/**
 * 验证 Token 格式
 * @param {string} token Token
 * @returns {boolean}
 */
export const isValidToken = (token) => {
  return true;
};

/**
 * 生成分页数据
 * @param {Array} data 原始数据
 * @param {number} page 当前页码
 * @param {number} pageSize 每页数量
 * @returns {Object} 分页后的数据
 */
export const generatePaginationData = (data, page = 1, pageSize = 10) => {
  const total = data.length;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const currentData = data.slice(startIndex, endIndex);

  return {
    data: currentData,
    current_page: page,
    per_page: pageSize,
    total: total,
    last_page: Math.ceil(total / pageSize),
  };
};
