import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import {
  IntegrationTestDatabase,
  setupIntegrationDatabaseHooks,
  TestDataFactory
} from '~/utils/server/integration-test-db';
import { IntegrationTestAssertions } from '~/utils/server/integration-test-utils';
import { ordersRoutesExport } from '@d8d/server/api';
import { AuthService } from '@d8d/server/modules/auth/auth.service';
import { UserService } from '@d8d/server/modules/users/user.service';
import { OrderStatus, PaymentStatus } from '@d8d/server/share/order.types';

// 设置集成测试钩子
setupIntegrationDatabaseHooks()

describe('用户端订单API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof ordersRoutesExport>>['api']['v1'];
  let testToken: string;
  let testUser: any;
  let testRoute: any;
  let testPassenger: any;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(ordersRoutesExport).api.v1;

    // 创建测试用户并生成token
    const dataSource = await IntegrationTestDatabase.getDataSource();

    const userService = new UserService(dataSource);
    const authService = new AuthService(userService);

    // 创建测试用户
    testUser = await TestDataFactory.createTestUser(dataSource);

    // 生成测试用户的token
    testToken = authService.generateToken(testUser);

    // 创建测试路线
    testRoute = await TestDataFactory.createTestRoute(dataSource);

    // 创建测试乘客
    testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
      userId: testUser.id,
      name: '测试乘客'
    });
  });

  describe('订单创建测试', () => {
    it('应该成功创建订单', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [
          {
            id: testPassenger.id,
            name: testPassenger.name,
            idType: testPassenger.idType,
            idNumber: testPassenger.idNumber,
            phone: testPassenger.phone
          }
        ],
        routeSnapshot: {
          id: testRoute.id,
          name: testRoute.name,
          pickupPoint: testRoute.pickupPoint,
          dropoffPoint: testRoute.dropoffPoint,
          departureTime: testRoute.departureTime,
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 断言响应
      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData).toHaveProperty('id');
        expect(responseData.userId).toBe(testUser.id);
        expect(responseData.routeId).toBe(orderData.routeId);
        expect(responseData.passengerCount).toBe(orderData.passengerCount);
        expect(responseData.totalAmount).toBe(orderData.totalAmount);
        expect(responseData.status).toBe(OrderStatus.PENDING_PAYMENT);
        expect(responseData.paymentStatus).toBe(PaymentStatus.PENDING);
        expect(responseData.passengerSnapshots).toEqual(orderData.passengerSnapshots);
        // 由于parseWithAwait会将Date转换为字符串，我们需要比较字符串格式
        const expectedRouteSnapshot = {
          ...orderData.routeSnapshot,
          departureTime: orderData.routeSnapshot.departureTime.toISOString()
        };
        expect(responseData.routeSnapshot).toEqual(expectedRouteSnapshot);

        // 断言数据库中存在订单
        await IntegrationTestAssertions.expectOrderToExist(responseData.id);
      } else {
        // 调试信息
        const errorData = await response.json();
        console.debug('订单创建失败:', errorData);
      }
    });

    it('应该拒绝创建不存在的路线订单', async () => {
      const orderData = {
        routeId: 999999, // 不存在的路线ID
        passengerCount: 1,
        totalAmount: 100,
        passengerSnapshots: [],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回404错误
      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('路线不存在');
      }
    });

    it('应该拒绝创建超过座位数的订单', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: testRoute.availableSeats + 1, // 超过可用座位数
        totalAmount: testRoute.price * (testRoute.availableSeats + 1),
        passengerSnapshots: [],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回422业务逻辑错误
      expect(response.status).toBe(422);
      if (response.status === 422) {
        const responseData = await response.json();
        expect(responseData.message).toContain('乘客数量超过路线座位数');
      }
    });

    it('应该验证乘客快照信息', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [
          {
            id: 999999, // 不存在的乘客ID
            name: '不存在的乘客',
            idType: 'ID_CARD',
            idNumber: '110101199001011234',
            phone: '13812345678'
          }
        ],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回404错误
      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('乘客ID 999999 不存在');
      }
    });

    it('应该拒绝创建缺少必填字段的订单', async () => {
      const orderData = {
        // 缺少routeId
        routeId: undefined as any, // 故意不提供routeId来测试验证
        passengerCount: 1,
        totalAmount: 100,
        passengerSnapshots: [],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回验证错误
      expect([400, 500]).toContain(response.status);
    });

    it('应该正确计算订单金额', async () => {
      const passengerCount = 2;
      const expectedTotalAmount = testRoute.price * passengerCount;

      const orderData = {
        routeId: testRoute.id,
        passengerCount: passengerCount,
        totalAmount: expectedTotalAmount,
        passengerSnapshots: [
          {
            id: testPassenger.id,
            name: testPassenger.name,
            idType: testPassenger.idType,
            idNumber: testPassenger.idNumber,
            phone: testPassenger.phone
          },
          {
            name: '第二个乘客',
            idType: 'ID_CARD',
            idNumber: '110101199001012345',
            phone: '13987654321'
          }
        ],
        routeSnapshot: {
          id: testRoute.id,
          name: testRoute.name,
          pickupPoint: testRoute.pickupPoint,
          dropoffPoint: testRoute.dropoffPoint,
          departureTime: testRoute.departureTime,
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData.totalAmount).toBe(expectedTotalAmount);
        expect(responseData.passengerCount).toBe(passengerCount);
      }
    });
  });

  describe('权限控制测试', () => {
    it('应该拒绝未认证用户的订单创建', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      });

      expect(response.status).toBe(401);
    });

    it('应该拒绝无效token的订单创建', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [],
        routeSnapshot: {}
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': 'Bearer invalid_token'
        }
      });

      expect(response.status).toBe(401);
    });
  });

  describe('快照机制测试', () => {
    it('应该正确保存路线快照信息', async () => {
      const routeSnapshot = {
        id: testRoute.id,
        name: testRoute.name,
        pickupPoint: testRoute.pickupPoint,
        dropoffPoint: testRoute.dropoffPoint,
        departureTime: testRoute.departureTime,
        price: testRoute.price,
        vehicleType: testRoute.vehicleType,
        travelMode: testRoute.travelMode
      };

      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [],
        routeSnapshot: routeSnapshot
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        // 由于parseWithAwait会将Date转换为字符串，我们需要比较字符串格式
        const expectedRouteSnapshot = {
          ...routeSnapshot,
          departureTime: routeSnapshot.departureTime.toISOString()
        };
        expect(responseData.routeSnapshot).toEqual(expectedRouteSnapshot);

        // 验证数据库中的快照数据
        const order = await IntegrationTestAssertions.getOrderById(responseData.id);
        expect(order).not.toBeNull();
        // 数据库中的routeSnapshot应该包含字符串格式的时间
        const expectedDbRouteSnapshot = {
          ...routeSnapshot,
          departureTime: routeSnapshot.departureTime.toISOString()
        };
        expect(order!.routeSnapshot).toEqual(expectedDbRouteSnapshot);
      }
    });

    it('应该正确保存乘客快照信息', async () => {
      const passengerSnapshots = [
        {
          id: testPassenger.id,
          name: testPassenger.name,
          idType: testPassenger.idType,
          idNumber: testPassenger.idNumber,
          phone: testPassenger.phone,
          isDefault: testPassenger.isDefault
        },
        {
          name: '新乘客',
          idType: 'PASSPORT',
          idNumber: 'E12345678',
          phone: '13987654321',
          isDefault: false
        }
      ];

      const orderData = {
        routeId: testRoute.id,
        passengerCount: passengerSnapshots.length,
        totalAmount: testRoute.price * passengerSnapshots.length,
        passengerSnapshots: passengerSnapshots,
        routeSnapshot: {
          id: testRoute.id,
          name: testRoute.name,
          pickupPoint: testRoute.pickupPoint,
          dropoffPoint: testRoute.dropoffPoint,
          departureTime: testRoute.departureTime,
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData.passengerSnapshots).toEqual(passengerSnapshots);

        // 验证数据库中的快照数据
        const order = await IntegrationTestAssertions.getOrderById(responseData.id);
        expect(order).not.toBeNull();
        expect(order!.passengerSnapshots).toEqual(passengerSnapshots);
      }
    });
  });

  describe('订单状态测试', () => {
    it('新创建的订单应该处于待支付状态', async () => {
      const orderData = {
        routeId: testRoute.id,
        passengerCount: 1,
        totalAmount: testRoute.price,
        passengerSnapshots: [],
        routeSnapshot: {
          id: testRoute.id,
          name: testRoute.name,
          pickupPoint: testRoute.pickupPoint,
          dropoffPoint: testRoute.dropoffPoint,
          departureTime: testRoute.departureTime,
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

      const response = await client.orders.$post({
        json: orderData,
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData.status).toBe(OrderStatus.PENDING_PAYMENT);
        expect(responseData.paymentStatus).toBe(PaymentStatus.PENDING);
      }
    });
  });
});