import { DataSource } from 'typeorm';
import { AreaEntity, AreaLevel } from '../../src/modules/areas/area.entity';

/**
 * 测试数据工厂类 - 专门用于地区模块测试
 */
export class TestDataFactory {
  /**
   * 创建测试区域数据
   */
  static createAreaData(overrides: Partial<AreaEntity> = {}): Partial<AreaEntity> {
    const timestamp = Date.now();
    return {
      name: `测试区域_${timestamp}`,
      code: `area_${timestamp}`,
      level: AreaLevel.PROVINCE,
      parentId: null,
      isDisabled: 0,
      isDeleted: 0,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试区域
   */
  static async createTestArea(dataSource: DataSource, overrides: Partial<AreaEntity> = {}): Promise<AreaEntity> {
    const areaData = this.createAreaData(overrides);
    const areaRepository = dataSource.getRepository(AreaEntity);

    // 对于顶级区域（省/直辖市），parentId应该为null
    if (areaData.level === AreaLevel.PROVINCE) {
      areaData.parentId = null;
    }
    // 对于市级区域，确保有对应的省级区域
    else if (areaData.level === AreaLevel.CITY && !areaData.parentId) {
      const province = await this.createTestArea(dataSource, { level: AreaLevel.PROVINCE });
      areaData.parentId = province.id;
    }
    // 对于区县级区域，确保有对应的市级区域
    else if (areaData.level === AreaLevel.DISTRICT && !areaData.parentId) {
      const city = await this.createTestArea(dataSource, { level: AreaLevel.CITY });
      areaData.parentId = city.id;
    }

    const area = areaRepository.create(areaData);
    return await areaRepository.save(area);
  }

  /**
   * 创建测试用户数据（用于认证测试）
   */
  static createUserData(overrides: any = {}): any {
    const timestamp = Date.now();
    return {
      id: Math.floor(Math.random() * 10000) + 1,
      username: `testuser_${timestamp}`,
      password: 'TestPassword123!',
      email: `test_${timestamp}@example.com`,
      phone: `138${timestamp.toString().slice(-8)}`,
      nickname: `Test User ${timestamp}`,
      name: `Test Name ${timestamp}`,
      isDisabled: 0,
      isDeleted: 0,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试用户（用于认证测试）
   */
  static async createTestUser(dataSource: DataSource, overrides: any = {}): Promise<any> {
    const userData = this.createUserData(overrides);

    // 导入 UserEntity
    const { UserEntity } = await import('@d8d/user-module');
    const userRepository = dataSource.getRepository(UserEntity);

    const user = userRepository.create(userData);
    return await userRepository.save(user);
  }
}