/**
 * Case Converter Utility
 * 自动转换 snake_case ↔ camelCase
 * 用于前端（camelCase）与后端 API（snake_case）之间的数据转换
 */

/**
 * 将 snake_case 字符串转换为 camelCase
 * @example snakeToCamel('user_id') → 'userId'
 */
export function snakeToCamel(str: string): string {
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

/**
 * 将 camelCase 字符串转换为 snake_case
 * @example camelToSnake('userId') → 'user_id'
 */
export function camelToSnake(str: string): string {
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}

/**
 * 深度转换对象的所有键从 snake_case 到 camelCase
 * @param obj - 要转换的对象（可能包含嵌套对象和数组）
 * @returns 转换后的对象
 */
export function keysToCamel<T = any>(obj: any): T {
  if (obj === null || obj === undefined) {
    return obj;
  }

  // 处理数组
  if (Array.isArray(obj)) {
    return obj.map(item => keysToCamel(item)) as any;
  }

  // 处理普通对象
  if (typeof obj === 'object' && obj.constructor === Object) {
    const converted: any = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        const camelKey = snakeToCamel(key);
        converted[camelKey] = keysToCamel(obj[key]);
      }
    }
    return converted;
  }

  // 其他类型（string, number, boolean 等）直接返回
  return obj;
}

/**
 * 深度转换对象的所有键从 camelCase 到 snake_case
 * @param obj - 要转换的对象（可能包含嵌套对象和数组）
 * @returns 转换后的对象
 */
export function keysToSnake<T = any>(obj: any, skipRecurseKeys?: Set<string>): T {
  if (obj === null || obj === undefined) {
    return obj;
  }

  // 处理数组
  if (Array.isArray(obj)) {
    return obj.map(item => keysToSnake(item, skipRecurseKeys)) as any;
  }

  // 处理普通对象
  if (typeof obj === 'object' && obj.constructor === Object) {
    const converted: any = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        const snakeKey = camelToSnake(key);
        if (skipRecurseKeys?.has(key)) {
          converted[snakeKey] = obj[key];
        } else {
          converted[snakeKey] = keysToSnake(obj[key], skipRecurseKeys);
        }
      }
    }
    return converted;
  }

  // 其他类型（string, number, boolean 等）直接返回
  return obj;
}

/**
 * 转换函数示例：
 * 
 * // API 响应 (snake_case) → 前端 (camelCase)
 * const apiResponse = {
 *   user_id: "123",
 *   created_at: "2025-01-01",
 *   user_profile: {
 *     first_name: "John"
 *   }
 * };
 * const frontendData = keysToCamel(apiResponse);
 * // { userId: "123", createdAt: "2025-01-01", userProfile: { firstName: "John" } }
 * 
 * // 前端 (camelCase) → API 请求 (snake_case)
 * const requestData = {
 *   userId: "123",
 *   firstName: "John"
 * };
 * const apiRequest = keysToSnake(requestData);
 * // { user_id: "123", first_name: "John" }
 */


