/**
 * 性能测试
 *
 * 验证凭证管理器的性能要求
 * - NFR-001: 配置文件加载 <100ms
 * - NFR-002: 签名操作 <50ms
 */

import { describe, test, expect, beforeEach, afterEach } from '@jest/globals';
import { CredentialManagerFactory, Platform } from '../../src/index';
import type { ICredentialManager } from '../../src/index';

describe('性能测试', () => {
  let manager: ICredentialManager;

  beforeEach(async () => {
    const factory = new CredentialManagerFactory();
    manager = await factory.create({
      enableFileWatching: false,
      enableLogging: false
    });

    // 添加测试账户
    await manager.addAccount({
      id: 'perf-test-001',
      platform: Platform.PACIFICA,
      credentials: {
        type: 'pacifica',
        privateKey: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
      }
    });
  });

  afterEach(async () => {
    await manager.destroy();
  });

  describe('NFR-002: 签名性能要求', () => {
    test('单次签名应在50ms内完成', async () => {
      const message = new TextEncoder().encode('performance test message');

      const startTime = Date.now();
      const result = await manager.sign('perf-test-001', message);
      const executionTime = Date.now() - startTime;

      expect(result.success).toBe(true);
      expect(executionTime).toBeLessThan(50);
      expect(result.executionTime).toBeLessThan(50);
    });

    test('批量签名平均时间应在50ms内', async () => {
      const message = new TextEncoder().encode('batch performance test');
      const batchSize = 10;
      const results: number[] = [];

      for (let i = 0; i < batchSize; i++) {
        const startTime = Date.now();
        const result = await manager.sign('perf-test-001', message);
        const executionTime = Date.now() - startTime;

        expect(result.success).toBe(true);
        results.push(executionTime);
      }

      const averageTime = results.reduce((sum, time) => sum + time, 0) / batchSize;
      expect(averageTime).toBeLessThan(50);

      console.log(`批量签名统计 (${batchSize}次):`);
      console.log(`  平均时间: ${averageTime.toFixed(2)}ms`);
      console.log(`  最快: ${Math.min(...results)}ms`);
      console.log(`  最慢: ${Math.max(...results)}ms`);
    });

    test('并发签名性能', async () => {
      const message = new TextEncoder().encode('concurrent performance test');
      const concurrency = 5;

      const startTime = Date.now();
      const promises = Array(concurrency).fill(0).map(() =>
        manager.sign('perf-test-001', message)
      );

      const results = await Promise.all(promises);
      const totalTime = Date.now() - startTime;

      // 所有签名都应该成功
      results.forEach(result => {
        expect(result.success).toBe(true);
        expect(result.executionTime).toBeLessThan(50);
      });

      // 并发执行的平均时间应该合理
      const averageTime = totalTime / concurrency;
      expect(averageTime).toBeLessThan(100); // 并发情况下允许稍高

      console.log(`并发签名统计 (${concurrency}个并发):`);
      console.log(`  总时间: ${totalTime}ms`);
      console.log(`  平均时间: ${averageTime.toFixed(2)}ms`);
    });
  });

  describe('统计功能性能', () => {
    test('获取统计信息应快速响应', async () => {
      const startTime = Date.now();
      const stats = await manager.getStats();
      const executionTime = Date.now() - startTime;

      expect(stats).toBeDefined();
      expect(stats.totalAccounts).toBeGreaterThan(0);
      expect(executionTime).toBeLessThan(10); // 统计查询应该很快

      console.log(`统计查询时间: ${executionTime}ms`);
    });

    test('大量账户下的性能', async () => {
      // 添加多个测试账户
      const accountCount = 50;
      for (let i = 0; i < accountCount; i++) {
        await manager.addAccount({
          id: `perf-account-${i}`,
          platform: Platform.PACIFICA,
          credentials: {
            type: 'pacifica',
            privateKey: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
          }
        });
      }

      // 测试listAccounts性能
      const startTime = Date.now();
      const accounts = manager.listAccounts();
      const listTime = Date.now() - startTime;

      expect(accounts.length).toBeGreaterThanOrEqual(accountCount);
      expect(listTime).toBeLessThan(10);

      // 测试统计性能
      const statsStartTime = Date.now();
      const stats = await manager.getStats();
      const statsTime = Date.now() - statsStartTime;

      expect(stats.totalAccounts).toBeGreaterThanOrEqual(accountCount);
      expect(statsTime).toBeLessThan(20);

      console.log(`大量账户性能 (${accountCount + 1}个账户):`);
      console.log(`  列表查询: ${listTime}ms`);
      console.log(`  统计查询: ${statsTime}ms`);
    });
  });
});