import { IntegrationTestDatabase } from '@d8d/shared-test-util';
import { MerchantMt } from '../../src/entities/merchant.mt.entity';

/**
 * 商户测试数据工厂
 * 用于创建商户测试数据，减少重复代码
 */
export class MerchantTestFactory {
  /**
   * 创建测试商户
   */
  static async createTestMerchant(
    createdBy: number,
    tenantId: number = 1,
    overrides: Partial<MerchantMt> = {}
  ): Promise<MerchantMt> {
    const dataSource = await IntegrationTestDatabase.getDataSource();
    const merchantRepository = dataSource.getRepository(MerchantMt);

    const timestamp = Date.now();
    const defaultMerchant = {
      name: `测试商户_${timestamp}`,
      username: `test_merchant_${timestamp}`,
      password: 'password123',
      phone: `13800138${timestamp.toString().slice(-4)}`,
      realname: '测试商户',
      state: 1,
      loginNum: 0,
      loginTime: 0,
      loginIp: '',
      lastLoginTime: 0,
      lastLoginIp: '',
      rsaPublicKey: '',
      aesKey: '',
      tenantId,
      createdBy
    };

    const merchantData = { ...defaultMerchant, ...overrides };
    const merchant = merchantRepository.create(merchantData);
    return await merchantRepository.save(merchant);
  }

  /**
   * 创建多个测试商户
   */
  static async createTestMerchants(
    createdBy: number,
    count: number,
    tenantId: number = 1,
    overrides: Partial<MerchantMt> = {}
  ): Promise<MerchantMt[]> {
    const merchants: MerchantMt[] = [];
    for (let i = 0; i < count; i++) {
      const merchant = await this.createTestMerchant(createdBy, tenantId, {
        ...overrides,
        name: `测试商户_${i + 1}`,
        username: `test_merchant_${i + 1}_${Date.now()}`
      });
      merchants.push(merchant);
    }
    return merchants;
  }

  /**
   * 创建不同租户的测试商户
   */
  static async createMultiTenantTestMerchants(
    createdBy: number,
    tenantIds: number[] = [1, 2]
  ): Promise<Record<number, MerchantMt[]>> {
    const result: Record<number, MerchantMt[]> = {};

    for (const tenantId of tenantIds) {
      const merchants = await this.createTestMerchants(createdBy, 2, tenantId, {
        name: `租户${tenantId}商户`
      });
      result[tenantId] = merchants;
    }

    return result;
  }

  /**
   * 创建测试商户数据集
   */
  static async createTestMerchantDataSet(
    userId: number,
    otherUserId: number,
    tenantId: number = 1
  ): Promise<{
    userMerchants: MerchantMt[];
    otherUserMerchants: MerchantMt[];
  }> {
    const userMerchants = await this.createTestMerchants(userId, 2, tenantId, {
      name: '用户商户'
    });

    const otherUserMerchants = await this.createTestMerchants(otherUserId, 1, tenantId, {
      name: '其他用户商户'
    });

    return {
      userMerchants,
      otherUserMerchants
    };
  }

  /**
   * 清理商户测试数据
   */
  static async cleanupMerchantTestData(): Promise<void> {
    const dataSource = await IntegrationTestDatabase.getDataSource();
    const merchantRepository = dataSource.getRepository(MerchantMt);
    await merchantRepository.clear();
  }
}