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 { Merchant } from '@d8d/merchant-module';
import { DeliveryAddress } from '@d8d/delivery-address-module';
import { AreaEntity } from '@d8d/geo-areas';
import { Supplier } from '@d8d/supplier-module';
import adminRefundsRoutes from '../../src/routes/admin/refunds';
import { Order, OrderRefund } from '../../src/entities';
import { OrdersTestDataFactory } from '../utils/test-data-factory';

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

describe('管理员退款管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof adminRefundsRoutes>>;
  let adminToken: string;
  let testUser: UserEntity;
  let testAdmin: UserEntity;
  let testOrder: Order;
  let otherUserOrder: Order;

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

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

    // 创建测试用户
    testUser = await OrdersTestDataFactory.createTestUser(dataSource);

    // 创建测试管理员用户
    testAdmin = await OrdersTestDataFactory.createTestUser(dataSource, {
      username: `test_admin_${Math.floor(Math.random() * 100000)}`,
      nickname: '测试管理员'
    });

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

    // 为测试用户创建完整的订单环境
    const testUserEnvironment = await OrdersTestDataFactory.createCompleteOrderEnvironment(dataSource, testUser.id);
    testOrder = testUserEnvironment.order;

    // 为管理员用户创建完整的订单环境
    const adminEnvironment = await OrdersTestDataFactory.createCompleteOrderEnvironment(dataSource, testAdmin.id);
    otherUserOrder = adminEnvironment.order;
  });

  describe('GET /refunds', () => {
    it('应该返回所有订单的退款列表', async () => {
      // 为不同用户的订单创建退款
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRefundRepository = dataSource.getRepository(OrderRefund);

      const userRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0,
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(userRefund);

      const adminRefund = orderRefundRepository.create({
        orderNo: otherUserOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 100.00,
        state: 1,
        createdBy: testAdmin.id,
        order: otherUserOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(adminRefund);

      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 userRefundCount = data.data.filter((refund: any) =>
          refund.order && refund.order.userId === testUser.id
        ).length;
        const adminRefundCount = data.data.filter((refund: any) =>
          refund.order && refund.order.userId === testAdmin.id
        ).length;

        expect(userRefundCount).toBeGreaterThan(0);
        expect(adminRefundCount).toBeGreaterThan(0);
      }
    });

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

  describe('POST /refunds', () => {
    it('应该成功创建退款申请并可以指定权限', async () => {
      const createData = {
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 75.00,
        state: 0,
        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.refundOrderNo).toBe(createData.refundOrderNo);
        expect(parseFloat(data.refundAmount)).toBe(createData.refundAmount);
        expect(data.state).toBe(createData.state);
        expect(data.createdBy).toBe(testAdmin.id); // 验证可以指定创建人
      }
    });

    it('应该验证创建退款申请的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        refundAmount: -1
      };

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

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

  describe('GET /refunds/:id', () => {
    it('应该返回指定退款的详情', async () => {
      // 先为测试用户的订单创建一个退款
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRefundRepository = dataSource.getRepository(OrderRefund);
      const testRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0,
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(testRefund);

      const response = await client[':id'].$get({
        param: { id: testRefund.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(testRefund.id);
        expect(data.refundOrderNo).toBe(testRefund.refundOrderNo);
        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 /refunds/:id', () => {
    it('应该成功更新任何退款', async () => {
      // 先为测试用户的订单创建一个退款
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRefundRepository = dataSource.getRepository(OrderRefund);
      const testRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0,
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(testRefund);

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

      const response = await client[':id'].$put({
        param: { id: testRefund.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.state).toBe(updateData.state);
        expect(data.updatedBy).toBe(testAdmin.id); // 验证可以指定更新人
      }
    });
  });

  describe('DELETE /refunds/:id', () => {
    it('应该成功删除任何退款', async () => {
      // 先为测试用户的订单创建一个退款
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRefundRepository = dataSource.getRepository(OrderRefund);
      const testRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0,
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(testRefund);

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

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

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

      // 创建不同用户的退款
      const userRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0,
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(userRefund);

      const adminRefund = orderRefundRepository.create({
        orderNo: otherUserOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 100.00,
        state: 0,
        createdBy: testAdmin.id,
        order: otherUserOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(adminRefund);

      // 使用管理员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 userRefundInResponse = data.data.filter((refund: any) =>
          refund.order && refund.order.userId === testUser.id
        );
        const adminRefundInResponse = data.data.filter((refund: any) =>
          refund.order && refund.order.userId === testAdmin.id
        );

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

  describe('退款状态管理测试', () => {
    it('应该正确处理退款状态变更', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderRefundRepository = dataSource.getRepository(OrderRefund);

      // 创建不同状态的退款
      const pendingRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 50.00,
        state: 0, // 未退款
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(pendingRefund);

      const processingRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 25.00,
        state: 1, // 退款中
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(processingRefund);

      const completedRefund = orderRefundRepository.create({
        orderNo: testOrder.orderNo,
        refundOrderNo: `REFUND_${Math.floor(Math.random() * 100000)}`,
        refundAmount: 75.00,
        state: 2, // 退款成功
        createdBy: testUser.id,
        order: testOrder // 设置关联的订单对象
      });
      await orderRefundRepository.save(completedRefund);

      // 验证状态过滤
      const response = await client.index.$get({
        query: { filters: JSON.stringify({ state: 0 }) }
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

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

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 应该只返回未退款状态的退款
        const pendingRefundsInResponse = data.data.filter((refund: any) => refund.state === 0);
        const processingRefundsInResponse = data.data.filter((refund: any) => refund.state === 1);
        const completedRefundsInResponse = data.data.filter((refund: any) => refund.state === 2);

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