import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
import { JWTUtil } from '@d8d/shared-utils';
import { UserEntity, Role } from '@d8d/user-module';
import { DeliveryAddress } from '@d8d/delivery-address-module';
import { AreaEntity } from '@d8d/geo-areas';
import { Merchant } from '@d8d/merchant-module';
import { Supplier } from '@d8d/supplier-module';
import { File } from '@d8d/file-module';
import userOrderRoutes from '../../src/routes/user/orders';
import { Order } from '../../src/entities';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntity, Role, Order, DeliveryAddress, Merchant, Supplier, File, AreaEntity
])

describe('用户订单管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof userOrderRoutes>>;
  let userToken: string;
  let otherUserToken: string;
  let testUser: UserEntity;
  let otherUser: UserEntity;
  let testDeliveryAddress: DeliveryAddress;
  let testMerchant: Merchant;
  let testSupplier: Supplier;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(userOrderRoutes);

    // 获取数据源
    const dataSource = await IntegrationTestDatabase.getDataSource();

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Math.floor(Math.random() * 100000)}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

    // 创建其他用户
    otherUser = userRepository.create({
      username: `other_user_${Math.floor(Math.random() * 100000)}`,
      password: 'other_password',
      nickname: '其他用户',
      registrationSource: 'web'
    });
    await userRepository.save(otherUser);

    // 生成测试用户的token
    userToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{name:'user'}]
    });

    // 生成其他用户的token
    otherUserToken = JWTUtil.generateToken({
      id: otherUser.id,
      username: otherUser.username,
      roles: [{name:'user'}]
    });

    // 创建测试区域数据
    const areaRepository = dataSource.getRepository(AreaEntity);
    const testProvince = areaRepository.create({
      name: '广东省',
      code: '440000',
      level: 1,
      parentId: null
    });
    await areaRepository.save(testProvince);

    const testCity = areaRepository.create({
      name: '深圳市',
      code: '440300',
      level: 2,
      parentId: testProvince.id
    });
    await areaRepository.save(testCity);

    const testDistrict = areaRepository.create({
      name: '南山区',
      code: '440305',
      level: 3,
      parentId: testCity.id
    });
    await areaRepository.save(testDistrict);

    const testTown = areaRepository.create({
      name: '粤海街道',
      code: '440305001',
      level: 3,
      parentId: testDistrict.id
    });
    await areaRepository.save(testTown);

    // 创建测试配送地址
    const deliveryAddressRepository = dataSource.getRepository(DeliveryAddress);
    testDeliveryAddress = deliveryAddressRepository.create({
      userId: testUser.id,
      name: '收货人姓名',
      phone: '13800138000',
      address: '测试地址',
      receiverProvince: testProvince.id,
      receiverCity: testCity.id,
      receiverDistrict: testDistrict.id,
      receiverTown: testTown.id,
      isDefault: 1,
      state: 1,
      createdBy: testUser.id
    });
    await deliveryAddressRepository.save(testDeliveryAddress);

    // 创建测试商户
    const merchantRepository = dataSource.getRepository(Merchant);
    testMerchant = merchantRepository.create({
      name: '测试商户',
      username: `test_merchant_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138001',
      realname: '测试商户',
      state: 1,
      createdBy: testUser.id
    });
    await merchantRepository.save(testMerchant);

    // 创建测试供应商
    const supplierRepository = dataSource.getRepository(Supplier);
    testSupplier = supplierRepository.create({
      name: '测试供应商',
      username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138002',
      realname: '测试供应商',
      state: 1,
      createdBy: testUser.id
    });
    await supplierRepository.save(testSupplier);
  });

  describe('GET /orders', () => {
    it('应该返回当前用户的订单列表', async () => {
      // 为测试用户创建一些订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);

      const userOrder1 = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(userOrder1);

      const userOrder2 = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 200.00,
        costAmount: 160.00,
        payAmount: 200.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 1,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(userOrder2);

      // 为其他用户创建一个订单，确保不会返回
      const otherUserOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: otherUser.id,
        amount: 300.00,
        costAmount: 240.00,
        payAmount: 300.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: otherUser.id
      });
      await orderRepository.save(otherUserOrder);

      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户订单列表响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户订单列表错误响应:', errorData);
      }
      expect(response.status).toBe(200);

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

        // 验证只返回当前用户的订单
        data.data.forEach((order: any) => {
          expect(order.userId).toBe(testUser.id);
        });

        // 验证不包含其他用户的订单
        const otherUserOrderInResponse = data.data.find((order: any) => order.userId === otherUser.id);
        expect(otherUserOrderInResponse).toBeUndefined();
      }
    });

    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      });
      expect(response.status).toBe(401);
    });
  });

  describe('POST /orders', () => {
    it('应该成功创建订单并自动设置当前用户权限', async () => {
      const createData = {
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        amount: 150.00,
        costAmount: 120.00,
        payAmount: 150.00,
        orderType: 1,
        payType: 1,
        payState: 0,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id
      };

      const response = await client.index.$post({
        json: createData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户创建订单响应状态:', response.status);
      if (response.status !== 201) {
        const errorData = await response.json();
        console.debug('用户创建订单错误响应:', errorData);
      }
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        expect(data).toHaveProperty('id');
        expect(data.orderNo).toBe(createData.orderNo);
        expect(parseFloat(data.amount)).toBe(createData.amount);
        expect(data.userId).toBe(testUser.id); // 验证自动设置当前用户权限
        expect(data.createdBy).toBe(testUser.id); // 验证自动设置创建用户
      }
    });

    it('应该验证创建订单的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        amount: -1,
        orderType: -1
      };

      const response = await client.index.$post({
        json: invalidData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

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

  describe('GET /orders/:id', () => {
    it('应该返回当前用户的订单详情', async () => {
      // 先为测试用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const testOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(testOrder);

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

      console.debug('用户订单详情响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户订单详情错误响应:', errorData);
      }
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testOrder.id);
        expect(data.orderNo).toBe(testOrder.orderNo);
        expect(data.userId).toBe(testUser.id);
      }
    });

    it('应该拒绝访问其他用户的订单', async () => {
      // 为其他用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const otherUserOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: otherUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: otherUser.id
      });
      await orderRepository.save(otherUserOrder);

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

      expect(response.status).toBe(403); // 数据权限控制返回403（权限不足）
    });

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

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

  describe('PUT /orders/:id', () => {
    it('应该成功更新当前用户的订单', async () => {
      // 先为测试用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const testOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(testOrder);

      const updateData = {
        state: 1,
        payState: 1
      };

      const response = await client[':id'].$put({
        param: { id: testOrder.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户更新订单响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.state).toBe(updateData.state);
        expect(data.payState).toBe(updateData.payState);
        expect(data.updatedBy).toBe(testUser.id); // 验证自动设置更新用户
      }
    });

    it('应该拒绝更新其他用户的订单', async () => {
      // 为其他用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const otherUserOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: otherUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: otherUser.id
      });
      await orderRepository.save(otherUserOrder);

      const updateData = {
        state: 1
      };

      const response = await client[':id'].$put({
        param: { id: otherUserOrder.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('DELETE /orders/:id', () => {
    it('应该成功删除当前用户的订单', async () => {
      // 先为测试用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const testOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(testOrder);

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

      console.debug('用户删除订单响应状态:', response.status);
      expect(response.status).toBe(204);
    });

    it('应该拒绝删除其他用户的订单', async () => {
      // 为其他用户创建一个订单
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);
      const otherUserOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: otherUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: otherUser.id
      });
      await orderRepository.save(otherUserOrder);

      const response = await client[':id'].$delete({
        param: { id: otherUserOrder.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('数据权限配置测试', () => {
    it('应该验证dataPermission配置正确工作', async () => {
      // 这个测试验证数据权限配置是否正常工作
      // 用户只能访问自己创建的订单

      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRepository = dataSource.getRepository(Order);

      // 创建测试用户和其他用户的订单
      const userOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: testUser.id,
        amount: 100.00,
        costAmount: 80.00,
        payAmount: 100.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: testUser.id
      });
      await orderRepository.save(userOrder);

      const otherUserOrder = orderRepository.create({
        orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
        userId: otherUser.id,
        amount: 200.00,
        costAmount: 160.00,
        payAmount: 200.00,
        orderType: 1,
        payType: 1,
        payState: 2,
        state: 0,
        addressId: testDeliveryAddress.id,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id,
        createdBy: otherUser.id
      });
      await orderRepository.save(otherUserOrder);

      // 使用测试用户token获取列表
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('数据权限配置测试错误响应:', errorData);
      }
      expect(response.status).toBe(200);
      const data = await response.json();

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 验证只返回测试用户的订单
        const userOrderInResponse = data.data.filter((order: any) => order.userId === testUser.id);
        const otherUserOrderInResponse = data.data.filter((order: any) => order.userId === otherUser.id);

        expect(userOrderInResponse.length).toBeGreaterThan(0);
        expect(otherUserOrderInResponse.length).toBe(0);
      } else {
        // 如果响应是错误格式，应该失败
        expect(data).toHaveProperty('data');
      }
    });
  });
});