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: {
          id: 999999,
          name: '不存在的路线',
          pickupPoint: '起点',
          dropoffPoint: '终点',
          departureTime: new Date(),
          price: 100,
          vehicleType: 'CAR',
          travelMode: 'DRIVING'
        }
      };

      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: {
          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}`
        }
      });

      // 应该返回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: {
          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}`
        }
      });

      // 应该返回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: {
          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([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: {
          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,
      });

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

    it('应该拒绝无效token的订单创建', 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 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);
      }
    });
  });

  describe('订单列表API测试', () => {
    let testOrder: any;

    beforeEach(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}`
        }
      });

      if (response.status === 201) {
        testOrder = await response.json();
      }
    });

    it('应该成功获取订单列表', async () => {
      const response = await client.orders.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData).toHaveProperty('data');
        expect(responseData).toHaveProperty('total');
        expect(responseData).toHaveProperty('page');
        expect(responseData).toHaveProperty('pageSize');
        expect(Array.isArray(responseData.data)).toBe(true);
        expect(responseData.data.length).toBeGreaterThan(0);

        // 验证订单数据格式
        const order = responseData.data[0];
        expect(order).toHaveProperty('id');
        expect(order).toHaveProperty('userId');
        expect(order).toHaveProperty('routeId');
        expect(order).toHaveProperty('status');
        expect(order).toHaveProperty('paymentStatus');
      }
    });

    it('应该支持按状态筛选订单', async () => {
      const response = await client.orders.$get({
        query: {
          page: 1,
          pageSize: 10,
          status: OrderStatus.PENDING_PAYMENT
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(Array.isArray(responseData.data)).toBe(true);

        // 验证所有返回的订单都是待支付状态
        if (responseData.data.length > 0) {
          responseData.data.forEach((order: any) => {
            expect(order.status).toBe(OrderStatus.PENDING_PAYMENT);
          });
        }
      }
    });

    it('应该支持分页功能', async () => {
      const pageSize = 5;
      const response = await client.orders.$get({
        query: {
          page: 1,
          pageSize: pageSize
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.page).toBe(1);
        expect(responseData.pageSize).toBe(pageSize);
        expect(responseData.data.length).toBeLessThanOrEqual(pageSize);
      }
    });

    it('应该拒绝未认证用户的订单列表请求', async () => {
      const response = await client.orders.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      });

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

  describe('订单详情API测试', () => {
    let testOrder: any;

    beforeEach(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}`
        }
      });

      if (response.status === 201) {
        testOrder = await response.json();
      }
    });

    it('应该成功获取订单详情', async () => {
      const response = await client.orders[':id'].$get({
        param: {
          id: testOrder.id
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.id).toBe(testOrder.id);
        expect(responseData.userId).toBe(testUser.id);
        expect(responseData.routeId).toBe(testRoute.id);
        expect(responseData.status).toBe(OrderStatus.PENDING_PAYMENT);
        expect(responseData.passengerSnapshots).toEqual(testOrder.passengerSnapshots);
        expect(responseData.routeSnapshot).toEqual(testOrder.routeSnapshot);
      }
    });

    it('应该拒绝查看不存在的订单', async () => {
      const response = await client.orders[':id'].$get({
        param: {
          id: 999999
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('订单不存在');
      }
    });

    it('应该拒绝查看其他用户的订单', async () => {
      // 创建另一个用户
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const userService = new UserService(dataSource);
      const authService = new AuthService(userService);

      const otherUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'other_user',
        phone: '13987654321'
      });
      const otherToken = authService.generateToken(otherUser);

      const response = await client.orders[':id'].$get({
        param: {
          id: testOrder.id
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${otherToken}`
        }
      });

      expect(response.status).toBe(403);
      if (response.status === 403) {
        const responseData = await response.json();
        expect(responseData.message).toContain('权限不足');
      }
    });

    it('应该拒绝未认证用户的订单详情请求', async () => {
      const response = await client.orders[':id'].$get({
        param: {
          id: testOrder.id
        }
      });

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

  describe('订单取消API测试', () => {
    let testOrder: any;

    beforeEach(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: new Date(Date.now() + 2 * 60 * 60 * 1000), // 2小时后出发
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

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

      if (response.status === 201) {
        testOrder = await response.json();

        // 更新订单状态为待出发
        const dataSource = await IntegrationTestDatabase.getDataSource();
        const orderRepository = dataSource.getRepository('Order');
        await orderRepository.update(testOrder.id, {
          status: OrderStatus.WAITING_DEPARTURE,
          paymentStatus: PaymentStatus.PAID
        });
      }
    });

    it('应该成功取消待出发状态的订单', async () => {
      const response = await client.orders[':id'].cancel.$post({
        param: {
          id: testOrder.id
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.id).toBe(testOrder.id);
        expect(responseData.status).toBe(OrderStatus.CANCELLED);
        expect(responseData.paymentStatus).toBe(PaymentStatus.REFUNDED);

        // 验证数据库中的状态更新
        const dataSource = await IntegrationTestDatabase.getDataSource();
        const orderRepository = dataSource.getRepository('Order');
        const updatedOrder = await orderRepository.findOne({
          where: { id: testOrder.id }
        });
        expect(updatedOrder?.status).toBe(OrderStatus.CANCELLED);
        expect(updatedOrder?.paymentStatus).toBe(PaymentStatus.REFUNDED);
      }
    });

    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: new Date(),
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

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

      if (createResponse.status === 201) {
        const completedOrder = await createResponse.json();

        // 更新订单状态为已完成
        const dataSource = await IntegrationTestDatabase.getDataSource();
        const orderRepository = dataSource.getRepository('Order');
        await orderRepository.update(completedOrder.id, {
          status: OrderStatus.COMPLETED,
          paymentStatus: PaymentStatus.PAID
        });

        const response = await client.orders[':id'].cancel.$post({
          param: {
            id: completedOrder.id
          }
        },
        {
          headers: {
            'Authorization': `Bearer ${testToken}`
          }
        });

        expect(response.status).toBe(422);
        if (response.status === 422) {
          const responseData = await response.json();
          expect(responseData.message).toContain('只能取消待出发状态的订单');
        }
      }
    });

    it('应该拒绝取消距离出发时间不足1小时的订单', 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: new Date(Date.now() + 30 * 60 * 1000), // 30分钟后出发
          price: testRoute.price,
          vehicleType: testRoute.vehicleType,
          travelMode: testRoute.travelMode
        }
      };

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

      if (createResponse.status === 201) {
        const urgentOrder = await createResponse.json();

        // 更新订单状态为待出发
        const dataSource = await IntegrationTestDatabase.getDataSource();
        const orderRepository = dataSource.getRepository('Order');
        await orderRepository.update(urgentOrder.id, {
          status: OrderStatus.WAITING_DEPARTURE,
          paymentStatus: PaymentStatus.PAID
        });

        const response = await client.orders[':id'].cancel.$post({
          param: {
            id: urgentOrder.id
          }
        },
        {
          headers: {
            'Authorization': `Bearer ${testToken}`
          }
        });

        expect(response.status).toBe(422);
        if (response.status === 422) {
          const responseData = await response.json();
          expect(responseData.message).toContain('距离出发时间不足1小时');
        }
      }
    });

    it('应该拒绝取消其他用户的订单', async () => {
      // 创建另一个用户
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const userService = new UserService(dataSource);
      const authService = new AuthService(userService);

      const otherUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'other_user',
        phone: '13987654321'
      });
      const otherToken = authService.generateToken(otherUser);

      const response = await client.orders[':id'].cancel.$post({
        param: {
          id: testOrder.id
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${otherToken}`
        }
      });

      expect(response.status).toBe(403);
      if (response.status === 403) {
        const responseData = await response.json();
        expect(responseData.message).toContain('权限不足');
      }
    });

    it('应该拒绝取消不存在的订单', async () => {
      const response = await client.orders[':id'].cancel.$post({
        param: {
          id: 999999
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('订单不存在');
      }
    });

    it('应该拒绝未认证用户的订单取消请求', async () => {
      const response = await client.orders[':id'].cancel.$post({
        param: {
          id: testOrder.id
        }
      });

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