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 { FileMt } from '@d8d/file-module-mt';
import { userSupplierRoutes } from '../../src/routes';
import { SupplierMt } from '../../src/entities';

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

describe('用户供应商管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof userSupplierRoutes>>;
  let userToken: string;
  let otherUserToken: string;
  let testUser: UserEntityMt;
  let otherUser: UserEntityMt;

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

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

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

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

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

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

  describe('GET /suppliers', () => {
    it('应该返回当前用户的供应商列表', async () => {
      // 为测试用户创建一些供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);

      const userSupplier1 = supplierRepository.create({
        tenantId: 1,
        name: '用户供应商1',
        username: `user_supplier1_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138001',
        realname: '用户供应商1',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(userSupplier1);

      const userSupplier2 = supplierRepository.create({
        tenantId: 1,
        name: '用户供应商2',
        username: `user_supplier2_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138002',
        realname: '用户供应商2',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(userSupplier2);

      // 为其他用户创建一个供应商，确保不会返回
      const otherUserSupplier = supplierRepository.create({
        tenantId: 1,
        name: '其他用户供应商',
        username: `other_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138003',
        realname: '其他用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: otherUser.id
      });
      await supplierRepository.save(otherUserSupplier);

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

      console.debug('用户供应商列表响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        if (data && 'data' in data) {
          expect(Array.isArray(data.data)).toBe(true);
          // 应该只返回当前用户的供应商
          data.data.forEach((supplier: any) => {
            expect(supplier.createdBy).toBe(testUser.id);
          });
        }
      }
    });

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

  describe('POST /suppliers', () => {
    it('应该成功创建供应商并自动使用当前用户ID', async () => {
      const createData = {
        name: '测试供应商',
        username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138000',
        realname: '测试供应商',
        state: 1
      };

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

      console.debug('用户创建供应商响应状态:', response.status);
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        console.debug('用户创建供应商响应数据:', JSON.stringify(data, null, 2));
        expect(data).toHaveProperty('id');
        expect(data.createdBy).toBe(testUser.id); // 自动使用当前用户ID
        expect(data.name).toBe(createData.name);
        expect(data.username).toBe(createData.username);
        expect(data.phone).toBe(createData.phone);
        expect(data.realname).toBe(createData.realname);
      }
    });

    it('应该验证创建供应商的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        name: '',
        username: '',
        password: '',
        phone: '',
        realname: ''
      };

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

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

  describe('GET /suppliers/:id', () => {
    it('应该返回当前用户的供应商详情', async () => {
      // 先为当前用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const testSupplier = supplierRepository.create({
        tenantId: 1,
        name: '测试供应商详情',
        username: `test_supplier_detail_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13600136000',
        realname: '测试供应商详情',
        loginNum: 5,
        loginTime: new Date('2024-01-01T12:00:00Z'),
        loginIp: '192.168.1.1',
        lastLoginTime: new Date('2024-01-01T12:00:00Z'),
        lastLoginIp: '192.168.1.1',
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(testSupplier);

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

      console.debug('用户供应商详情响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testSupplier.id);
        expect(data.createdBy).toBe(testUser.id);
        expect(data.name).toBe(testSupplier.name);
        expect(data.username).toBe(testSupplier.username);
        expect(data.phone).toBe(testSupplier.phone);
        expect(data.realname).toBe(testSupplier.realname);
      }
    });

    it('应该拒绝访问其他用户的供应商', async () => {
      // 为其他用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const otherUserSupplier = supplierRepository.create({
        tenantId: 1,
        name: '其他用户供应商',
        username: `other_supplier_detail_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13600136001',
        realname: '其他用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: otherUser.id
      });
      await supplierRepository.save(otherUserSupplier);

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

      console.debug('用户访问其他用户供应商响应状态:', response.status);
      expect(response.status).toBe(404); // 应该返回404，而不是403
    });

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

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

  describe('PUT /suppliers/:id', () => {
    it('应该成功更新当前用户的供应商', async () => {
      // 先为当前用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const testSupplier = supplierRepository.create({
        tenantId: 1,
        name: '原始供应商',
        username: `original_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13500135000',
        realname: '原始供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(testSupplier);

      const updateData = {
        name: '更新后的供应商',
        phone: '13700137000',
        realname: '更新后的供应商',
        state: 2
      };

      const response = await client[':id'].$put({
        param: { id: testSupplier.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.name).toBe(updateData.name);
        expect(data.phone).toBe(updateData.phone);
        expect(data.realname).toBe(updateData.realname);
        expect(data.state).toBe(updateData.state);
      }
    });

    it('应该拒绝更新其他用户的供应商', async () => {
      // 为其他用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const otherUserSupplier = supplierRepository.create({
        tenantId: 1,
        name: '其他用户供应商',
        username: `other_supplier_update_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13500135001',
        realname: '其他用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: otherUser.id
      });
      await supplierRepository.save(otherUserSupplier);

      const updateData = {
        name: '尝试更新的供应商',
        phone: '13700137001',
        realname: '尝试更新的供应商'
      };

      // 当前用户尝试更新其他用户的供应商
      const response = await client[':id'].$put({
        param: { id: otherUserSupplier.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户更新其他用户供应商响应状态:', response.status);
      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('DELETE /suppliers/:id', () => {
    it('应该成功删除当前用户的供应商', async () => {
      // 先为当前用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const testSupplier = supplierRepository.create({
        tenantId: 1,
        name: '待删除供应商',
        username: `delete_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13400134000',
        realname: '待删除供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(testSupplier);

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

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

      // 验证供应商确实被删除
      const deletedSupplier = await supplierRepository.findOne({
        where: { id: testSupplier.id }
      });
      expect(deletedSupplier).toBeNull();
    });

    it('应该拒绝删除其他用户的供应商', async () => {
      // 为其他用户创建一个供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const otherUserSupplier = supplierRepository.create({
        tenantId: 1,
        name: '其他用户供应商',
        username: `other_supplier_delete_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13400134001',
        realname: '其他用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: otherUser.id
      });
      await supplierRepository.save(otherUserSupplier);

      // 当前用户尝试删除其他用户的供应商
      const response = await client[':id'].$delete({
        param: { id: otherUserSupplier.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户删除其他用户供应商响应状态:', response.status);
      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('数据权限验证', () => {
    it('用户应该只能访问和操作自己的数据', async () => {
      // 为两个用户都创建供应商
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const supplierRepository = dataSource.getRepository(SupplierMt);

      const userSupplier = supplierRepository.create({
        tenantId: 1,
        name: '用户供应商',
        username: `user_supplier_perm_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138004',
        realname: '用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(userSupplier);

      const otherUserSupplier = supplierRepository.create({
        tenantId: 1,
        name: '其他用户供应商',
        username: `other_supplier_perm_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138005',
        realname: '其他用户供应商',
        loginNum: 0,
        loginTime: null,
        loginIp: null,
        lastLoginTime: null,
        lastLoginIp: null,
        state: 1,
        createdBy: otherUser.id
      });
      await supplierRepository.save(otherUserSupplier);

      // 当前用户应该只能看到自己的供应商
      const listResponse = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(listResponse.status).toBe(200);
      const listData = await listResponse.json();
      if (listData && 'data' in listData) {
        expect(Array.isArray(listData.data)).toBe(true);
        // 应该只包含当前用户的供应商
        listData.data.forEach((supplier: any) => {
          expect(supplier.createdBy).toBe(testUser.id);
        });
      }

      // 当前用户应该无法访问其他用户的供应商详情
      const getResponse = await client[':id'].$get({
        param: { id: otherUserSupplier.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });
      expect(getResponse.status).toBe(404);

      // 当前用户应该无法更新其他用户的供应商
      const updateResponse = await client[':id'].$put({
        param: { id: otherUserSupplier.id },
        json: { name: '尝试更新' }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });
      expect(updateResponse.status).toBe(403);

      // 当前用户应该无法删除其他用户的供应商
      const deleteResponse = await client[':id'].$delete({
        param: { id: otherUserSupplier.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });
      expect(deleteResponse.status).toBe(403);
    });
  });

  describe('供应商状态管理', () => {
    it('应该支持供应商状态管理', async () => {
      // 创建启用状态的供应商
      const createData = {
        name: '状态测试供应商',
        username: `status_test_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138006',
        realname: '状态测试供应商',
        state: 1 // 启用状态
      };

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

      expect(createResponse.status).toBe(201);
      const createdData = await createResponse.json();

      // 更新为禁用状态
      if (typeof createdData === 'object' && createdData !== null && 'id' in createdData) {
        const updateResponse = await client[':id'].$put({
          param: { id: createdData.id },
          json: { state: 2 } // 禁用状态
        }, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        expect(updateResponse.status).toBe(200);
        const updatedData = await updateResponse.json();
        if (typeof updatedData === 'object' && updatedData !== null && 'state' in updatedData) {
          expect(updatedData.state).toBe(2);
        }
      }
    });
  });

  describe('供应商登录统计', () => {
    it('应该支持供应商登录统计功能', async () => {
      // 创建供应商
      const createData = {
        name: '登录统计供应商',
        username: `login_stat_supplier_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138007',
        realname: '登录统计供应商',
        state: 1
      };

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

      expect(createResponse.status).toBe(201);
      const createdData = await createResponse.json();

      // 验证初始登录统计
      if (typeof createdData === 'object' && createdData !== null) {
        if ('loginNum' in createdData) expect(createdData.loginNum).toBe(0);
        if ('loginTime' in createdData) expect(createdData.loginTime).toBeNull();
        if ('lastLoginTime' in createdData) expect(createdData.lastLoginTime).toBeNull();
        if ('loginIp' in createdData) expect(createdData.loginIp).toBeNull();
        if ('lastLoginIp' in createdData) expect(createdData.lastLoginIp).toBeNull();
      }

      // 获取供应商详情验证字段存在
      if (typeof createdData === 'object' && createdData !== null && 'id' in createdData) {
        const getResponse = await client[':id'].$get({
          param: { id: createdData.id }
        }, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        expect(getResponse.status).toBe(200);
        const supplierData = await getResponse.json();
        if (typeof supplierData === 'object' && supplierData !== null) {
          expect(supplierData).toHaveProperty('loginNum');
          expect(supplierData).toHaveProperty('loginTime');
          expect(supplierData).toHaveProperty('lastLoginTime');
          expect(supplierData).toHaveProperty('loginIp');
          expect(supplierData).toHaveProperty('lastLoginIp');
        }
      }
    });
  });

  describe('跨租户数据隔离', () => {
    let tenant2UserToken: string;
    let tenant2User: UserEntityMt;

    beforeEach(async () => {
      // 获取数据源
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const userRepository = dataSource.getRepository(UserEntityMt);

      // 创建租户2的用户
      tenant2User = userRepository.create({
        username: `tenant2_user_${Math.floor(Math.random() * 100000)}`,
        password: 'test_password',
        nickname: '租户2用户',
        registrationSource: 'web',
        tenantId: 2
      });
      await userRepository.save(tenant2User);

      // 生成租户2用户的token
      tenant2UserToken = JWTUtil.generateToken({
        id: tenant2User.id,
        username: tenant2User.username,
        roles: [],
        tenantId: tenant2User.tenantId
      });

      // 为租户1创建一些供应商
      const supplierRepository = dataSource.getRepository(SupplierMt);
      const tenant1Supplier1 = supplierRepository.create({
        name: '租户1供应商1',
        username: `tenant1_supplier1_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138008',
        realname: '租户1供应商1',
        state: 1,
        tenantId: 1,
        createdBy: testUser.id
      });
      await supplierRepository.save(tenant1Supplier1);

      // 为租户2创建一些供应商
      const tenant2Supplier1 = supplierRepository.create({
        name: '租户2供应商1',
        username: `tenant2_supplier1_${Math.floor(Math.random() * 100000)}`,
        password: 'password123',
        phone: '13800138009',
        realname: '租户2供应商1',
        state: 1,
        tenantId: 2,
        createdBy: tenant2User.id
      });
      await supplierRepository.save(tenant2Supplier1);
    });

    it('应该实现租户数据隔离 - 租户1用户只能看到租户1的供应商', async () => {
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

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

      // 验证租户1用户只能看到租户1的供应商
      if (data.data && Array.isArray(data.data)) {
        data.data.forEach((supplier: any) => {
          expect(supplier.tenantId).toBe(1);
          expect(supplier.createdBy).toBe(testUser.id);
        });
      }
    });

    it('应该实现租户数据隔离 - 租户2用户只能看到租户2的供应商', async () => {
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${tenant2UserToken}`
        }
      });

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

      // 验证租户2用户只能看到租户2的供应商
      if (data.data && Array.isArray(data.data)) {
        data.data.forEach((supplier: any) => {
          expect(supplier.tenantId).toBe(2);
          expect(supplier.createdBy).toBe(tenant2User.id);
        });
      }
    });

    it('应该阻止跨租户访问供应商详情', async () => {
      // 获取租户1的供应商列表
      const listResponse = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(listResponse.status).toBe(200);
      const listData = await listResponse.json();

      if (listData.data && Array.isArray(listData.data) && listData.data.length > 0) {
        const tenant1SupplierId = listData.data[0].id;

        // 租户2用户尝试访问租户1的供应商
        const getResponse = await client[':id'].$get({
          param: { id: tenant1SupplierId }
        }, {
          headers: {
            'Authorization': `Bearer ${tenant2UserToken}`
          }
        });

        // 跨租户访问应该返回404
        expect(getResponse.status).toBe(404);
      }
    });

    it('应该阻止跨租户更新供应商', async () => {
      // 获取租户1的供应商列表
      const listResponse = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(listResponse.status).toBe(200);
      const listData = await listResponse.json();

      if (listData.data && Array.isArray(listData.data) && listData.data.length > 0) {
        const tenant1SupplierId = listData.data[0].id;

        // 租户2用户尝试更新租户1的供应商
        const updateResponse = await client[':id'].$put({
          param: { id: tenant1SupplierId },
          json: { name: '跨租户更新测试' }
        }, {
          headers: {
            'Authorization': `Bearer ${tenant2UserToken}`
          }
        });

        // 跨租户更新应该返回404
        expect(updateResponse.status).toBe(404);
      }
    });

    it('应该阻止跨租户删除供应商', async () => {
      // 获取租户1的供应商列表
      const listResponse = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(listResponse.status).toBe(200);
      const listData = await listResponse.json();

      if (listData.data && Array.isArray(listData.data) && listData.data.length > 0) {
        const tenant1SupplierId = listData.data[0].id;

        // 租户2用户尝试删除租户1的供应商
        const deleteResponse = await client[':id'].$delete({
          param: { id: tenant1SupplierId }
        }, {
          headers: {
            'Authorization': `Bearer ${tenant2UserToken}`
          }
        });

        // 跨租户删除应该返回404
        expect(deleteResponse.status).toBe(404);
      }
    });
  });
});