import { describe, it, expect, beforeAll, afterAll } from '@jest/globals';
const request = require('supertest');
import { app } from '../../test-app';

describe('并发压力测试', () => {
  const concurrentUsers = 50;
  const requestsPerUser = 10;
  const totalRequests = concurrentUsers * requestsPerUser;

  it(`应该能够处理 ${totalRequests} 个并发请求`, async () => {
    const promises = [];

    for (let i = 0; i < concurrentUsers; i++) {
      for (let j = 0; j < requestsPerUser; j++) {
        const promise = request(app)
          .get('/api/v1/products')
          .set('x-tenant-id', `test-tenant-${i}`)
          .set('x-trace-id', `trace-${i}-${j}`)
          .expect('Content-Type', /json/)
          .expect(200)
          .then((response: any) => {
            expect(response.body.success).toBe(true);
            expect(response.body.data).toBeInstanceOf(Array);
            expect(response.body.traceId).toBe(`trace-${i}-${j}`);
            expect(response.body.tenantId).toBe(`test-tenant-${i}`);
          });

        promises.push(promise);
      }
    }

    const results = await Promise.allSettled(promises);
    const failedTests = results.filter(result => result.status === 'rejected');

    expect(failedTests.length).toBe(0);
    console.log(`成功处理 ${totalRequests} 个并发请求`);
  });

  it('应该在高并发下保持响应时间稳定', async () => {
    const responseTimes = [];

    for (let i = 0; i < 100; i++) {
      const start = Date.now();
      await request(app)
        .get('/api/v1/products')
        .set('x-tenant-id', 'test-tenant')
        .set('x-trace-id', `trace-${i}`)
        .expect(200);
      const end = Date.now();
      responseTimes.push(end - start);
    }

    const averageResponseTime = responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length;
    const maxResponseTime = Math.max(...responseTimes);

    console.log(`平均响应时间: ${averageResponseTime.toFixed(2)}ms`);
    console.log(`最大响应时间: ${maxResponseTime}ms`);

    expect(averageResponseTime).toBeLessThan(500);
    expect(maxResponseTime).toBeLessThan(2000);
  });

  it('应该能够处理并发订单创建请求', async () => {
    const promises = [];

    for (let i = 0; i < 20; i++) {
      const promise = request(app)
        .post('/api/v1/orders')
        .set('x-tenant-id', 'test-tenant')
        .set('x-trace-id', `order-trace-${i}`)
        .send({
          userId: 'test-user',
          items: [
            {
              productId: 'test-product-1',
              quantity: 1
            }
          ],
          totalAmount: 99.99
        })
        .expect('Content-Type', /json/)
        .expect(200)
        .then((response: any) => {
          expect(response.body.success).toBe(true);
          expect(response.body.data.orderId).toBeDefined();
          expect(response.body.traceId).toBe(`order-trace-${i}`);
        });

      promises.push(promise);
    }

    const results = await Promise.allSettled(promises);
    const failedTests = results.filter(result => result.status === 'rejected');

    expect(failedTests.length).toBe(0);
    console.log('成功处理20个并发订单创建请求');
  });
});
