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 { File } from '@d8d/file-module';
import { Goods, GoodsCategory } from '@d8d/goods-module';
import { Supplier } from '@d8d/supplier-module';
import { Merchant } from '@d8d/merchant-module';
import { DeliveryAddress } from '@d8d/delivery-address-module';
import { AreaEntity } from '@d8d/geo-areas';
import adminOrderItemsRoutes from '../../src/routes/admin/order-items';
import { Order, OrderGoods } from '../../src/entities';

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

describe('管理员订单商品管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof adminOrderItemsRoutes>>;
  let adminToken: string;
  let testUser: UserEntity;
  let testAdmin: UserEntity;
  let testOrder: Order;
  let otherUserOrder: Order;
  let testGoods: Goods;
  let testSupplier: Supplier;
  let testFile: File;

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

    // 获取数据源
    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);

    // 创建测试管理员用户
    testAdmin = userRepository.create({
      username: `test_admin_${Math.floor(Math.random() * 100000)}`,
      password: 'admin_password',
      nickname: '测试管理员',
      registrationSource: 'web'
    });
    await userRepository.save(testAdmin);

    // 生成测试管理员的token
    adminToken = JWTUtil.generateToken({
      id: testAdmin.id,
      username: testAdmin.username,
      roles: [{name:'admin'}]
    });

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

    // 创建测试文件
    const fileRepository = dataSource.getRepository(File);
    testFile = fileRepository.create({
      name: 'test_image.jpg',
      type: 'image/jpeg',
      size: 102400,
      path: 'images/test_image.jpg',
      uploadUserId: testUser.id,
      uploadTime: new Date(),
      createdAt: new Date(),
      updatedAt: new Date()
    });
    await fileRepository.save(testFile);

    // 创建测试商品分类
    const categoryRepository = dataSource.getRepository(GoodsCategory);
    const testCategory = categoryRepository.create({
      name: '测试分类',
      level: 1,
      sort: 1,
      state: 1,
      createdBy: testUser.id
    });
    await categoryRepository.save(testCategory);

    // 创建测试商品
    const goodsRepository = dataSource.getRepository(Goods);
    testGoods = goodsRepository.create({
      name: '测试商品',
      price: 100.00,
      costPrice: 80.00,
      categoryId1: testCategory.id,
      categoryId2: testCategory.id,
      categoryId3: testCategory.id,
      goodsType: 1,
      supplierId: testSupplier.id,
      imageFileId: testFile.id,
      state: 1,
      stock: 100,
      lowestBuy: 1,
      createdBy: testUser.id
    });
    await goodsRepository.save(testGoods);

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

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

    const testCity = areaRepository.create({
      name: '广州市',
      level: 2,
      code: '4401',
      state: 1
    });
    await areaRepository.save(testCity);

    const testDistrict = areaRepository.create({
      name: '天河区',
      level: 3,
      code: '440106',
      state: 1
    });
    await areaRepository.save(testDistrict);

    const testTown = areaRepository.create({
      name: '天河南街道',
      level: 4,
      code: '440106001',
      state: 1
    });
    await areaRepository.save(testTown);

    // 创建测试配送地址
    const addressRepository = dataSource.getRepository(DeliveryAddress);
    const testDeliveryAddress = addressRepository.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 addressRepository.save(testDeliveryAddress);

    // 创建测试用户的订单
    const orderRepository = dataSource.getRepository(Order);
    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,
      recevierProvince: testProvince.id,
      recevierCity: testCity.id,
      recevierDistrict: testDistrict.id,
      recevierTown: testTown.id,
      createdBy: testUser.id
    });
    await orderRepository.save(testOrder);

    // 创建其他用户的订单
    otherUserOrder = orderRepository.create({
      orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
      userId: testAdmin.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,
      recevierProvince: testProvince.id,
      recevierCity: testCity.id,
      recevierDistrict: testDistrict.id,
      recevierTown: testTown.id,
      createdBy: testAdmin.id
    });
    await orderRepository.save(otherUserOrder);
  });

  describe('GET /order-items', () => {
    it('应该返回所有订单的商品列表', async () => {
      // 为不同用户的订单创建商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);

      const userOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        orderNo: testOrder.orderNo,
        goodsId: testGoods.id,
        goodsName: '测试用户商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(userOrderGoods);

      const adminOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        orderNo: otherUserOrder.orderNo,
        goodsId: testGoods.id,
        goodsName: '管理员用户商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testAdmin.id
      });
      await orderGoodsRepository.save(adminOrderGoods);

      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

      console.debug('管理员订单商品列表响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('管理员订单商品列表错误响应:', JSON.stringify(errorData, null, 2));
      }
      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);

        // 验证返回所有用户的订单商品（管理员可以访问所有数据）
        const userOrderGoodsCount = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === testUser.id
        ).length;
        const adminOrderGoodsCount = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === testAdmin.id
        ).length;

        expect(userOrderGoodsCount).toBeGreaterThan(0);
        expect(adminOrderGoodsCount).toBeGreaterThan(0);
      }
    });

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

  describe('POST /order-items', () => {
    it('应该成功创建订单商品并可以指定权限', async () => {
      const createData = {
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '管理员创建商品',
        price: 75.00,
        num: 3,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testAdmin.id // 管理员可以指定创建人
      };

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

      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.goodsName).toBe(createData.goodsName);
        expect(parseFloat(data.price)).toBe(createData.price);
        expect(data.num).toBe(createData.num);
        expect(data.createdBy).toBe(testAdmin.id); // 验证可以指定创建人
      }
    });

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

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

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

  describe('GET /order-items/:id', () => {
    it('应该返回指定订单商品的详情', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        orderNo: testOrder.orderNo,
        goodsId: testGoods.id,
        goodsName: '测试订单商品详情',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

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

      console.debug('管理员订单商品详情响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testOrderGoods.id);
        expect(data.goodsName).toBe(testOrderGoods.goodsName);
        expect(data.order.userId).toBe(testUser.id); // 验证可以访问其他用户的订单商品
      }
    });

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

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

  describe('PUT /order-items/:id', () => {
    it('应该成功更新任何订单商品', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试更新订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

      const updateData = {
        num: 5,
        state: 1,
        updatedBy: testAdmin.id // 管理员可以指定更新人
      };

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

      console.debug('管理员更新订单商品响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.num).toBe(updateData.num);
        expect(data.state).toBe(updateData.state);
        expect(data.updatedBy).toBe(testAdmin.id); // 验证可以指定更新人
      }
    });
  });

  describe('DELETE /order-items/:id', () => {
    it('应该成功删除任何订单商品', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试删除订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

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

      console.debug('管理员删除订单商品响应状态:', response.status);
      expect(response.status).toBe(204);
    });
  });

  describe('管理员权限验证测试', () => {
    it('应该验证管理员可以访问所有数据', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);

      // 创建不同用户的订单商品
      const userOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        orderNo: testOrder.orderNo,
        goodsId: testGoods.id,
        goodsName: '用户订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(userOrderGoods);

      const adminOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        orderNo: otherUserOrder.orderNo,
        goodsId: testGoods.id,
        goodsName: '管理员订单商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testAdmin.id
      });
      await orderGoodsRepository.save(adminOrderGoods);

      // 使用管理员token获取列表
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

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

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 验证返回所有用户的订单商品
        const userOrderGoodsInResponse = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === testUser.id
        );
        const adminOrderGoodsInResponse = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === testAdmin.id
        );

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