import { describe, it, expect, beforeEach, vi, afterEach } 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 { bankNameRoutes } from '../../src/routes/bank-names';
import { BankName } from '../../src/entities/bank-name.entity';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([UserEntity, File, Role, BankName])

describe('银行名称管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof bankNameRoutes>>;
  let testToken: string;
  let testUser: UserEntity;

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

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

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Date.now()}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

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

  describe('GET /bank-names', () => {
    it('应该返回银行名称列表', async () => {
      const response = await client.index.$get({
        query: {

        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      console.debug('银行名称列表响应状态:', response.status);
      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);
      }
    });

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

  describe('POST /bank-names', () => {
    it('应该成功创建银行名称', async () => {
      const createData = {
        name: '测试银行名称',
        code: 'test_type',
        remark: '测试备注',
        status: 1
      };

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

      console.debug('创建银行名称响应状态:', response.status);
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        expect(data).toHaveProperty('id');
        expect(data.name).toBe(createData.name);
        expect(data.code).toBe(createData.code);
        expect(data.status).toBe(createData.status);
      }
    });

    it('应该验证创建银行名称的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        name: '',
        code: '',
        remark: '测试备注'
      };

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

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

    it('应该验证银行名称编码的唯一性', async () => {
      // 先创建一个银行名称
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const bankNameRepository = dataSource.getRepository(BankName);
      const existingType = bankNameRepository.create({
        name: '现有类型',
        code: 'existing_code',
        status: 1
      });
      await bankNameRepository.save(existingType);

      // 尝试创建相同编码的类型
      const duplicateData = {
        name: '重复类型',
        code: 'existing_code', // 重复的编码
        status: 1
      };

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

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

  describe('GET /bank-names/:id', () => {
    it('应该返回指定银行名称的详情', async () => {
      // 先创建一个银行名称
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const bankNameRepository = dataSource.getRepository(BankName);
      const testType = bankNameRepository.create({
        name: '测试类型详情',
        code: 'test_type_detail',
        remark: '测试备注',
        status: 1
      });
      await bankNameRepository.save(testType);

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

      console.debug('银行名称详情响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testType.id);
        expect(data.name).toBe(testType.name);
        expect(data.code).toBe(testType.code);
      }
    });

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

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

  describe('PUT /bank-names/:id', () => {
    it('应该成功更新银行名称', async () => {
      // 先创建一个银行名称
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const bankNameRepository = dataSource.getRepository(BankName);
      const testType = bankNameRepository.create({
        name: '原始类型',
        code: 'original_type',
        remark: '原始备注',
        status: 1
      });
      await bankNameRepository.save(testType);

      const updateData = {
        name: '更新后的类型',
        code: 'updated_type',
        remark: '更新后的备注'
      };

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

      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.code).toBe(updateData.code);
        expect(data.remark).toBe(updateData.remark);
      }
    });
  });

  describe('DELETE /bank-names/:id', () => {
    it('应该成功删除银行名称', async () => {
      // 先创建一个银行名称
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const bankNameRepository = dataSource.getRepository(BankName);
      const testType = bankNameRepository.create({
        name: '待删除类型',
        code: 'delete_type',
        remark: '待删除备注',
        status: 1
      });
      await bankNameRepository.save(testType);

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

      console.debug('删除银行名称响应状态:', response.status);
      expect(response.status).toBe(204);

      // 验证银行名称确实被删除
      const deletedType = await bankNameRepository.findOne({
        where: { id: testType.id }
      });
      expect(deletedType).toBeNull();
    });
  });
});