/**
 * 类型保护工具函数
 */

/**
 * 检查值是否为有效的数字
 */
export function isValidNumber(value: unknown): value is number {
  return typeof value === 'number' && !isNaN(value) && isFinite(value);
}

/**
 * 检查值是否为有效的字符串
 */
export function isValidString(value: unknown): value is string {
  return typeof value === 'string' && value.length > 0;
}

/**
 * 检查对象是否有有效的 ID
 */
export function hasValidId(obj: unknown): obj is { id: number } {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    'id' in obj &&
    isValidNumber((obj as any).id)
  );
}

/**
 * 安全获取数字值，提供默认值
 */
export function safeNumber(value: unknown, defaultValue = 0): number {
  if (isValidNumber(value)) {
    return value;
  }
  if (typeof value === 'string') {
    const parsed = Number(value);
    return isValidNumber(parsed) ? parsed : defaultValue;
  }
  return defaultValue;
}

/**
 * 安全获取字符串值，提供默认值
 */
export function safeString(value: unknown, defaultValue = ''): string {
  return typeof value === 'string' ? value : defaultValue;
}

/**
 * 检查 API 响应是否有效
 */
export function isValidApiResponse<T>(
  response: unknown
): response is { count: number; list?: T[] } {
  return (
    typeof response === 'object' &&
    response !== null &&
    'count' in response &&
    isValidNumber((response as any).count)
  );
}

/**
 * 检查统计数据是否有效
 */
export function isValidStatistics(data: unknown): data is {
  id?: number;
  userCount?: number;
  orderCount?: number;
  totalSales?: number;
} {
  return typeof data === 'object' && data !== null;
}

/**
 * 安全的对象合并，过滤掉 undefined 值
 */
export function safeMerge<T extends Record<string, any>>(
  target: T,
  source: Partial<T>
): T {
  const result = { ...target };

  for (const [key, value] of Object.entries(source)) {
    if (value !== undefined) {
      result[key as keyof T] = value;
    }
  }

  return result;
}

/**
 * 创建带有默认值的对象
 */
export function withDefaults<T extends Record<string, any>>(
  data: Partial<T>,
  defaults: T
): T {
  return safeMerge(defaults, data);
}
