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 { UserEntityMt, RoleMt } from '@d8d/user-module-mt';
import { DeliveryAddressMt } from '@d8d/delivery-address-module-mt';
import { AreaEntityMt } from '@d8d/geo-areas-mt';
import { MerchantMt } from '@d8d/merchant-module-mt';
import { SupplierMt } from '@d8d/supplier-module-mt';
import { FileMt } from '@d8d/file-module-mt';
import { GoodsMt, GoodsCategoryMt } from '@d8d/goods-module-mt';
import userOrderRoutes from '../../src/routes/user/orders.mt';
import { OrderMt, OrderGoodsMt } from '../../src/entities';
import { OrdersTestFactory } from '../factories/orders-test-factory';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntityMt, RoleMt, OrderMt, OrderGoodsMt, DeliveryAddressMt, MerchantMt, SupplierMt, FileMt, AreaEntityMt, GoodsMt, GoodsCategoryMt
])

describe('多租户用户订单管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof userOrderRoutes>>;
  let testFactory: OrdersTestFactory;
  let userToken: string;
  let otherUserToken: string;
  let otherTenantUserToken: string;
  let testUser: UserEntityMt;
  let otherUser: UserEntityMt;
  let otherTenantUser: UserEntityMt;

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

    // 获取数据源并创建测试工厂
    const dataSource = await IntegrationTestDatabase.getDataSource();
    testFactory = new OrdersTestFactory(dataSource);

    // 创建测试用户
    testUser = await testFactory.createTestUser(1);
    otherUser = await testFactory.createTestUser(1);
    otherTenantUser = await testFactory.createTestUser(2);

    // 生成JWT令牌
    userToken = JWTUtil.generateToken({ id: testUser.id, username: testUser.username, tenantId: 1 });
    otherUserToken = JWTUtil.generateToken({ id: otherUser.id, username: otherUser.username, tenantId: 1 });
    otherTenantUserToken = JWTUtil.generateToken({ id: otherTenantUser.id, username: otherTenantUser.username, tenantId: 2 });
  });

  describe('租户数据隔离验证', () => {
    it('应该只能访问自己租户的订单', async () => {
      // 创建租户1的订单
      const tenant1Order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });

      // 创建租户2的订单
      const tenant2Order = await testFactory.createTestOrder(otherTenantUser.id, { tenantId: 2 });

      // 使用租户1的用户查询订单列表
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });


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

        // 应该只返回租户1的订单
        expect(data.data).toHaveLength(1);
        expect(data.data[0].tenantId).toBe(1);
        expect(data.data[0].id).toBe(tenant1Order.id);
      }
      });

    it('不应该访问其他租户的订单详情', async () => {
      // 创建租户2的订单
      const otherTenantOrder = await testFactory.createTestOrder(otherTenantUser.id, { tenantId: 2 });

      // 使用租户1的用户尝试访问租户2的订单
      const response = await client[':id'].$get({
        param: { id: otherTenantOrder.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回404，因为订单不在当前租户
      expect(response.status).toBe(404);
    });

    it('应该正确过滤跨租户订单访问', async () => {
      // 创建租户1的订单
      const tenant1Order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });

      // 使用租户2的用户尝试访问租户1的订单
      const response = await client[':id'].$get({
        param: { id: tenant1Order.id }
      }, {
        headers: {
          'Authorization': `Bearer ${otherTenantUserToken}`
        }
      });

      // 应该返回404，因为订单不在当前租户
      expect(response.status).toBe(404);
    });
  });

  describe('用户数据权限验证', () => {
    it('应该只能访问自己的订单', async () => {
      // 创建当前用户的订单
      const myOrder = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });

      // 创建其他用户的订单（同一租户）
      const otherUserOrder = await testFactory.createTestOrder(otherUser.id, { tenantId: 1 });

      // 使用当前用户查询订单列表
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

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

        // 应该只返回当前用户的订单
        expect(data.data).toHaveLength(1);
        expect(data.data[0].userId).toBe(testUser.id);
        expect(data.data[0].id).toBe(myOrder.id);
      }
    });

    it('不应该访问其他用户的订单详情', async () => {
      // 创建其他用户的订单
      const otherUserOrder = await testFactory.createTestOrder(otherUser.id, { tenantId: 1 });
      console.debug('创建的订单:', { id: otherUserOrder.id, userId: otherUserOrder.userId, tenantId: otherUserOrder.tenantId });

      // 使用当前用户尝试访问其他用户的订单
      const response = await client[':id'].$get({
        param: { id: otherUserOrder.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回403，因为无权访问其他用户的订单
      console.debug('响应状态码:', response.status);
      expect(response.status).toBe(403);
    });
  });

  describe('订单商品关联验证', () => {
    it('应该返回包含订单商品信息的订单详情', async () => {
      // 创建测试订单和订单商品
      const order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });
      const testGoods = await testFactory.createTestGoods(testUser.id, { tenantId: 1 });
      const orderGoods = await testFactory.createTestOrderGoods(order.id, testGoods.id, { tenantId: 1 });

      // 查询订单详情
      const response = await client[':id'].$get({
        param: { id: order.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const orderDetail = await response.json();

        // 验证订单详情包含订单商品信息
        expect(orderDetail.orderGoods).toBeDefined();
        expect(Array.isArray(orderDetail.orderGoods)).toBe(true);
        expect(orderDetail.orderGoods).toHaveLength(1);

        const goods = orderDetail.orderGoods[0];
        expect(goods.id).toBe(orderGoods.id);
        expect(goods.goodsId).toBe(orderGoods.goodsId);
        expect(goods.goodsName).toBe(orderGoods.goodsName);
        expect(goods.price).toBe(Number(orderGoods.price));
        expect(goods.num).toBe(orderGoods.num);
      }
    });

    it('应该返回包含订单商品信息的订单列表', async () => {
      // 创建测试订单和订单商品
      const order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });
      const testGoods = await testFactory.createTestGoods(testUser.id, { tenantId: 1 });
      await testFactory.createTestOrderGoods(order.id, testGoods.id, { tenantId: 1 });

      // 查询订单列表
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

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

        // 验证订单列表包含订单商品信息
        expect(data.data).toHaveLength(1);
        expect(data.data[0].orderGoods).toBeDefined();
        expect(Array.isArray(data.data[0].orderGoods)).toBe(true);
        expect(data.data[0].orderGoods).toHaveLength(1);

        const goods = data.data[0].orderGoods[0];
        expect(goods.goodsId).toBeGreaterThan(0);
        expect(goods.goodsName).toBeDefined();
        expect(goods.price).toBeGreaterThan(0);
        expect(goods.num).toBeGreaterThan(0);
      }
    });
  });

  describe('订单创建验证', () => {
    it('应该自动设置租户ID', async () => {
      // 创建必要的关联实体
      const testSupplier = await testFactory.createTestSupplier(testUser.id, { tenantId: 1 });
      const testMerchant = await testFactory.createTestMerchant(testUser.id, { tenantId: 1 });
      const testDeliveryAddress = await testFactory.createTestDeliveryAddress(testUser.id, { tenantId: 1 });
      const testGoods = await testFactory.createTestGoods(testUser.id, {
        tenantId: 1,
        merchantId: testMerchant.id,
        supplierId: testSupplier.id
      });

      const orderData = {
        addressId: testDeliveryAddress.id,
        productOwn: '自营',
        consumeFrom: '积分兑换',
        products: [
          { id: testGoods.id, num: 2 }
        ]
      };

      const response = await client['create-order'].$post({
        json: orderData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

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

        // 验证订单创建成功
        expect(createdOrder.success).toBe(true);
        expect(createdOrder.orderId).toBeGreaterThan(0);
        expect(createdOrder.orderNo).toBeDefined();
        expect(createdOrder.amount).toBeGreaterThan(0);
        expect(createdOrder.payAmount).toBeGreaterThan(0);
      }
    });
  });

  describe('取消订单功能验证', () => {
    it('应该成功取消未支付订单', async () => {
      // 创建未支付订单
      const order = await testFactory.createTestOrder(testUser.id, {
        tenantId: 1,
        payState: 0, // 未支付
        state: 0
      });

      const cancelData = {
        orderId: order.id,
        reason: '用户主动取消'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const result = await response.json();

        expect(result.success).toBe(true);
        expect(result.message).toBe('订单取消成功');
      }

      // 验证订单状态已更新
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const updatedOrder = await dataSource.getRepository(OrderMt).findOne({
        where: { id: order.id, tenantId: 1 }
      });

      expect(updatedOrder?.payState).toBe(5); // 订单关闭
      expect(updatedOrder?.cancelReason).toBe('用户主动取消');
      expect(updatedOrder?.cancelTime).toBeInstanceOf(Date);
    });

    it('应该成功取消已支付订单', async () => {
      // 创建已支付订单
      const order = await testFactory.createTestOrder(testUser.id, {
        tenantId: 1,
        payState: 2, // 支付成功
        state: 0
      });

      const cancelData = {
        orderId: order.id,
        reason: '用户主动取消（已支付）'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const result = await response.json();

        expect(result.success).toBe(true);
        expect(result.message).toBe('订单取消成功');
      }

      // 验证订单状态已更新
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const updatedOrder = await dataSource.getRepository(OrderMt).findOne({
        where: { id: order.id, tenantId: 1 }
      });

      expect(updatedOrder?.payState).toBe(5); // 订单关闭
      expect(updatedOrder?.cancelReason).toBe('用户主动取消（已支付）');
      expect(updatedOrder?.cancelTime).toBeInstanceOf(Date);
    });

    it('应该拒绝取消不允许的订单状态', async () => {
      // 创建已发货订单（支付状态=2，订单状态=1）
      const order = await testFactory.createTestOrder(testUser.id, {
        tenantId: 1,
        payState: 2, // 支付成功
        state: 1 // 已发货
      });

      const cancelData = {
        orderId: order.id,
        reason: '尝试取消已发货订单'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回403，因为已发货订单不允许取消
      expect(response.status).toBe(403);
      if (response.status === 403) {
        const result = await response.json();

        expect(result.message).toBe('当前订单状态不允许取消');
      }
    });

    it('应该拒绝取消不存在的订单', async () => {
      const cancelData = {
        orderId: 99999, // 不存在的订单ID
        reason: '取消不存在的订单'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回404
      expect(response.status).toBe(404);
      if (response.status === 404) {
        const result = await response.json();

        expect(result.message).toBe('订单不存在');
      }
    });

    it('应该拒绝跨租户取消订单', async () => {
      // 创建租户2的订单
      const otherTenantOrder = await testFactory.createTestOrder(otherTenantUser.id, {
        tenantId: 2,
        payState: 0
      });

      const cancelData = {
        orderId: otherTenantOrder.id,
        reason: '跨租户取消尝试'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回404，因为订单不在当前租户
      expect(response.status).toBe(404);
      if (response.status === 404) {
        const result = await response.json();

        expect(result.message).toBe('订单不存在');
      }
    });

    it('应该拒绝跨用户取消订单', async () => {
      // 创建其他用户的订单（同一租户）
      const otherUserOrder = await testFactory.createTestOrder(otherUser.id, {
        tenantId: 1,
        payState: 0
      });

      const cancelData = {
        orderId: otherUserOrder.id,
        reason: '跨用户取消尝试'
      };

      const response = await client['cancel-order'].$post({
        json: cancelData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      // 应该返回404，因为无权访问其他用户的订单
      expect(response.status).toBe(404);
      const result = await response.json();

      expect(result.message).toBe('订单不存在');
    });
  });
});