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 userOrderRoutes from '../../src/routes/user/orders.mt';
import { OrderMt } from '../../src/entities';
import { OrdersTestFactory } from '../factories/orders-test-factory';

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

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.orders.$get({}, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('Response status:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('Error response:', errorData);
      }

      expect(response.status).toBe(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.orders[':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.orders[':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.orders.$get({}, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(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 });

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

      // 应该返回403，因为无权访问其他用户的订单
      expect(response.status).toBe(403);
    });
  });

  describe('订单创建验证', () => {
    it('应该自动设置租户ID', async () => {
      const orderData = {
        orderNo: `ORD_${Date.now()}`,
        amount: 100.00,
        payAmount: 95.00,
        discountAmount: 5.00,
        merchantId: 1,
        supplierId: 1,
        addressId: 1
      };

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

      expect(response.status).toBe(201);
      const createdOrder = await response.json();

      // 验证租户ID已正确设置
      expect(createdOrder.tenantId).toBe(1);
      expect(createdOrder.userId).toBe(testUser.id);
    });
  });
});