/**
 * Performance Testing Utilities (v2.1)
 * 
 * 性能测试辅助工具
 * 
 * 基于文档: docs/modules/organization/09-test-scenarios.md - 性能监控辅助函数
 */

/**
 * 性能计时器
 */
export class PerformanceTimer {
  private startTime: number;

  start() {
    this.startTime = Date.now();
  }

  end(): number {
    return Date.now() - this.startTime;
  }

  async measure<T>(fn: () => Promise<T>): Promise<{ result: T; duration: number }> {
    this.start();
    const result = await fn();
    const duration = this.end();
    return { result, duration };
  }
}

/**
 * 批量性能测试
 */
export async function runPerformanceTest(
  testName: string,
  fn: () => Promise<void>,
  iterations: number = 10,
) {
  const durations: number[] = [];

  for (let i = 0; i < iterations; i++) {
    const timer = new PerformanceTimer();
    const { duration } = await timer.measure(fn);
    durations.push(duration);
  }

  const avg = durations.reduce((a, b) => a + b, 0) / durations.length;
  const min = Math.min(...durations);
  const max = Math.max(...durations);

  console.log(`\n[Performance] ${testName}`);
  console.log(`  Avg: ${avg.toFixed(2)}ms`);
  console.log(`  Min: ${min}ms`);
  console.log(`  Max: ${max}ms`);

  return { avg, min, max, durations };
}

/**
 * 并发测试辅助函数
 */
export async function runConcurrentRequests<T>(
  fn: () => Promise<T>,
  count: number,
): Promise<T[]> {
  const promises = Array.from({ length: count }, () => fn());
  return await Promise.all(promises);
}

/**
 * 内存使用监控
 */
export function getMemoryUsage() {
  const usage = process.memoryUsage();
  return {
    heapUsed: (usage.heapUsed / 1024 / 1024).toFixed(2) + ' MB',
    heapTotal: (usage.heapTotal / 1024 / 1024).toFixed(2) + ' MB',
    external: (usage.external / 1024 / 1024).toFixed(2) + ' MB',
    rss: (usage.rss / 1024 / 1024).toFixed(2) + ' MB',
  };
}

/**
 * 性能断言辅助函数
 */
export function assertPerformance(
  duration: number,
  maxDuration: number,
  testName: string,
) {
  if (duration > maxDuration) {
    throw new Error(
      `Performance test "${testName}" failed: ${duration}ms > ${maxDuration}ms`,
    );
  }
}

