import 'dart:math';
import 'package:superport/data/models/user/user_dto.dart';
import 'package:superport/data/models/equipment/equipment_request.dart';
import 'package:superport/data/models/license/license_request_dto.dart';
import 'package:superport/data/models/warehouse/warehouse_dto.dart';
import 'package:superport/models/company_model.dart';
import 'package:superport/models/user_model.dart';
import 'package:superport/models/equipment_unified_model.dart';
import 'package:superport/models/warehouse_location_model.dart';
import 'package:superport/models/license_model.dart';
import 'package:superport/models/address_model.dart';
import 'package:superport/services/company_service.dart';
import 'package:superport/services/user_service.dart';
import 'package:superport/services/equipment_service.dart';
import 'package:superport/services/license_service.dart';
import 'package:superport/services/warehouse_service.dart';
import 'package:get_it/get_it.dart';
import '../models/test_models.dart';

/// 스마트한 테스트 데이터 생성기
/// 
/// 기존 TestDataHelper를 확장하여 더 현실적이고 관계성 있는 테스트 데이터를 생성합니다.
class TestDataGenerator {
  static final Random _random = Random();
  static int _uniqueId = DateTime.now().millisecondsSinceEpoch;
  
  // 캐싱을 위한 맵
  static final Map<String, dynamic> _cache = {};
  static final List<int> _createdCompanyIds = [];
  static final List<int> _createdUserIds = [];
  static final List<int> _createdWarehouseIds = [];
  static final List<int> _createdEquipmentIds = [];
  static final List<int> _createdLicenseIds = [];
  
  // 실제 데이터 풀
  static const List<String> _realCompanyNames = [
    '테크솔루션',
    '디지털컴퍼니',
    '스마트시스템즈',
    '클라우드테크',
    '데이터브릭스',
    '소프트웨어파크',
    'IT이노베이션',
    '퓨처테크놀로지',
  ];
  
  static const List<String> _realManufacturers = [
    '삼성전자',
    'LG전자',
    'Apple',
    'Dell',
    'HP',
    'Lenovo',
    'Microsoft',
    'ASUS',
  ];
  
  static const Map<String, List<String>> _realProductModels = {
    '삼성전자': ['Galaxy Book Pro', 'Galaxy Book Pro 360', 'Odyssey G9', 'ViewFinity S9'],
    'LG전자': ['Gram 17', 'Gram 16', 'UltraGear 27GN950', 'UltraFine 32UN880'],
    'Apple': ['MacBook Pro 16"', 'MacBook Air M2', 'iMac 24"', 'Mac Studio'],
    'Dell': ['XPS 13', 'XPS 15', 'Latitude 7420', 'OptiPlex 7090'],
    'HP': ['Spectre x360', 'EliteBook 840', 'ZBook Studio', 'ProBook 450'],
    'Lenovo': ['ThinkPad X1 Carbon', 'ThinkPad T14s', 'IdeaPad 5', 'Legion 5'],
    'Microsoft': ['Surface Laptop 5', 'Surface Pro 9', 'Surface Studio 2+'],
    'ASUS': ['ZenBook 14', 'ROG Zephyrus G14', 'ProArt StudioBook'],
  };
  
  static const List<String> _categories = [
    '노트북',
    '데스크탑',
    '모니터',
    '프린터',
    '네트워크장비',
    '서버',
    '태블릿',
    '스캐너',
  ];
  
  static const List<String> _warehouseNames = [
    '메인창고',
    '서브창고A',
    '서브창고B',
    '임시보관소',
    '수리센터',
    '대여센터',
  ];
  
  static const List<String> _softwareProducts = [
    'Microsoft Office 365',
    'Adobe Creative Cloud',
    'AutoCAD 2024',
    'Windows 11 Pro',
    'Visual Studio Enterprise',
    'JetBrains All Products',
    'Slack Business+',
    'Zoom Business',
  ];
  
  static const List<String> _departments = [
    '개발팀',
    '디자인팀',
    '영업팀',
    '인사팀',
    '재무팀',
    '마케팅팀',
    '운영팀',
  ];
  
  static const List<String> _positions = [
    '팀장',
    '매니저',
    '선임',
    '주임',
    '사원',
    '인턴',
  ];
  
  // 유틸리티 메서드
  static String generateUniqueId() {
    return '${_uniqueId++}';
  }
  
  static String generateUniqueEmail({String? domain}) {
    domain ??= 'test.com';
    return 'test_${generateUniqueId()}@$domain';
  }
  
  static String generateUniqueName(String prefix) {
    return '${prefix}_${generateUniqueId()}';
  }
  
  static String generatePhoneNumber() {
    final area = ['010', '011', '016', '017', '018', '019'][_random.nextInt(6)];
    final middle = 1000 + _random.nextInt(9000);
    final last = 1000 + _random.nextInt(9000);
    return '$area-$middle-$last';
  }
  
  static String generateBusinessNumber() {
    final first = 100 + _random.nextInt(900);
    final second = 10 + _random.nextInt(90);
    final third = 10000 + _random.nextInt(90000);
    return '$first-$second-$third';
  }
  
  static T getRandomElement<T>(List<T> list) {
    return list[_random.nextInt(list.length)];
  }
  
  // 추가 메서드들 (인스턴스 메서드로 변경)
  String generateId() => generateUniqueId();
  
  String generateSerialNumber() {
    final prefix = ['SN', 'EQ', 'IT'][_random.nextInt(3)];
    final year = DateTime.now().year;
    final number = _random.nextInt(999999).toString().padLeft(6, '0');
    return '$prefix-$year-$number';
  }
  
  String generateEquipmentName() {
    final manufacturers = ['삼성', 'LG', 'Dell', 'HP', 'Lenovo'];
    final types = ['노트북', '데스크탑', '모니터', '프린터', '서버'];
    final models = ['Pro', 'Elite', 'Plus', 'Standard', 'Premium'];
    return '${getRandomElement(manufacturers)} ${getRandomElement(types)} ${getRandomElement(models)}';
  }
  
  String generateCompanyName() {
    final prefixes = ['테크', '디지털', '스마트', '글로벌', '퓨처'];
    final suffixes = ['솔루션', '시스템', '컴퍼니', '테크놀로지', '이노베이션'];
    return '${getRandomElement(prefixes)}${getRandomElement(suffixes)} ${generateUniqueId()}';
  }
  
  double generatePrice({double min = 100000, double max = 10000000}) {
    return min + (_random.nextDouble() * (max - min));
  }
  
  String generateAddress() {
    final cities = ['서울시', '부산시', '대구시', '인천시', '광주시'];
    final districts = ['강남구', '서초구', '송파구', '마포구', '중구'];
    final streets = ['테헤란로', '강남대로', '디지털로', '한강대로', '올림픽로'];
    final number = _random.nextInt(500) + 1;
    return '${getRandomElement(cities)} ${getRandomElement(districts)} ${getRandomElement(streets)} $number';
  }
  
  String generatePostalCode() {
    return '${10000 + _random.nextInt(90000)}';
  }
  
  String generatePersonName() {
    final lastNames = ['김', '이', '박', '최', '정', '강', '조', '윤', '장', '임'];
    final firstNames = ['민수', '영희', '철수', '영미', '준호', '지은', '성민', '수진', '현우', '민지'];
    return '${getRandomElement(lastNames)}${getRandomElement(firstNames)}';
  }
  
  String generateEmail() => generateUniqueEmail();
  
  String generateUsername() {
    final adjectives = ['smart', 'clever', 'quick', 'bright', 'sharp'];
    final nouns = ['user', 'admin', 'manager', 'developer', 'designer'];
    return '${getRandomElement(adjectives)}_${getRandomElement(nouns)}_${generateUniqueId()}';
  }
  
  String generateLicenseKey() {
    final segments = [];
    for (int i = 0; i < 4; i++) {
      final segment = _random.nextInt(9999).toString().padLeft(4, '0').toUpperCase();
      segments.add(segment);
    }
    return segments.join('-');
  }
  
  String generateSoftwareName() {
    return getRandomElement(_softwareProducts);
  }
  
  // 회사 데이터 생성
  static Company createSmartCompanyData({
    String? name,
    List<CompanyType>? companyTypes,
  }) {
    name ??= '${getRandomElement(_realCompanyNames)} ${generateUniqueId()}';
    
    return Company(
      name: name,
      address: Address(
        region: '서울시 강남구',
        detailAddress: '테헤란로 ${100 + _random.nextInt(400)}',
      ),
      contactName: '홍길동',
      contactPosition: '대표이사',
      contactPhone: generatePhoneNumber(),
      contactEmail: generateUniqueEmail(domain: 'company.com'),
      companyTypes: companyTypes ?? [CompanyType.customer],
      remark: '테스트 회사 - ${DateTime.now().toIso8601String()}',
    );
  }
  
  // 사용자 데이터 생성
  static CreateUserRequest createSmartUserData({
    required int companyId,
    int? branchId,
    String? role,
    String? department,
    String? position,
  }) {
    final firstName = ['김', '이', '박', '최', '정', '강', '조', '윤'][_random.nextInt(8)];
    final lastName = ['민수', '영희', '철수', '영미', '준호', '지은', '성민', '수진'][_random.nextInt(8)];
    final fullName = '$firstName$lastName';
    
    department ??= getRandomElement(_departments);
    position ??= getRandomElement(_positions);
    
    return CreateUserRequest(
      username: 'user_${generateUniqueId()}',
      email: generateUniqueEmail(domain: 'company.com'),
      password: 'Test1234!@',
      name: fullName,
      phone: generatePhoneNumber(),
      role: role ?? 'staff',
      companyId: companyId,
      branchId: branchId,
    );
  }
  
  // 장비 데이터 생성
  static CreateEquipmentRequest createSmartEquipmentData({
    required int companyId,
    required int warehouseLocationId,
    String? category,
    String? manufacturer,
    String? status,
  }) {
    final String actualManufacturer = manufacturer ?? getRandomElement(_realManufacturers);
    final models = _realProductModels[actualManufacturer] ?? ['Standard Model'];
    final model = getRandomElement(models);
    final String actualCategory = category ?? getRandomElement(_categories);
    
    final serialNumber = '${actualManufacturer.length >= 2 ? actualManufacturer.substring(0, 2).toUpperCase() : actualManufacturer.toUpperCase()}'
        '${DateTime.now().year}'
        '${_random.nextInt(1000000).toString().padLeft(6, '0')}';
    
    return CreateEquipmentRequest(
      equipmentNumber: 'EQ-${generateUniqueId()}',
      category1: actualCategory,
      category2: _getCategoryDetail(actualCategory),
      manufacturer: actualManufacturer,
      modelName: model,
      serialNumber: serialNumber,
      purchaseDate: DateTime.now().subtract(Duration(days: _random.nextInt(365))),
      purchasePrice: _getRealisticPrice(actualCategory),
      remark: '테스트 장비 - $model',
    );
  }
  
  // 라이선스 데이터 생성
  static CreateLicenseRequest createSmartLicenseData({
    required int companyId,
    int? branchId,
    String? productName,
    String? licenseType,
  }) {
    productName ??= getRandomElement(_softwareProducts);
    final vendor = _getVendorFromProduct(productName!);
    
    return CreateLicenseRequest(
      licenseKey: 'LIC-${generateUniqueId()}-${_random.nextInt(9999).toString().padLeft(4, '0')}',
      productName: productName,
      vendor: vendor,
      licenseType: licenseType ?? 'subscription',
      userCount: [1, 5, 10, 25, 50, 100][_random.nextInt(6)],
      purchaseDate: DateTime.now().subtract(Duration(days: _random.nextInt(180))),
      expiryDate: DateTime.now().add(Duration(days: 30 + _random.nextInt(335))),
      purchasePrice: _getLicensePrice(productName),
      companyId: companyId,
      branchId: branchId,
      remark: '테스트 라이선스 - $productName',
    );
  }
  
  // 창고 데이터 생성
  static CreateWarehouseLocationRequest createSmartWarehouseData({
    String? name,
    int? managerId,
  }) {
    name ??= '${getRandomElement(_warehouseNames)} ${generateUniqueId()}';
    
    return CreateWarehouseLocationRequest(
      name: name,
      address: '서울시 강남구 물류로 ${_random.nextInt(100) + 1}',
      city: '서울',
      state: '서울특별시',
      postalCode: '${10000 + _random.nextInt(90000)}',
      country: '대한민국',
      capacity: [100, 200, 500, 1000, 2000][_random.nextInt(5)],
      managerId: managerId,
    );
  }
  
  // 시나리오별 데이터 세트 생성
  
  /// 장비 입고 시나리오 데이터 생성
  static Future<EquipmentScenarioData> createEquipmentScenario({
    int? equipmentCount = 5,
  }) async {
    final companyService = GetIt.I<CompanyService>();
    final warehouseService = GetIt.I<WarehouseService>();
    final equipmentService = GetIt.I<EquipmentService>();
    
    // 1. 회사 생성
    final companyData = createSmartCompanyData(
      name: '테크장비관리 주식회사',
      companyTypes: [CompanyType.customer],
    );
    
    final company = await companyService.createCompany(companyData);
    _createdCompanyIds.add(company.id!);
    
    // 2. 창고 생성
    final warehouseData = createSmartWarehouseData(
      name: '중앙 물류센터',
    );
    
    // warehouseService가 WarehouseLocation을 받는지 확인 필요
    // 일단 WarehouseLocation으로 변환
    final warehouseLocation = WarehouseLocation(
      id: 0,  // id 필수, 서비스에서 생성될 예정
      name: warehouseData.name,
      address: Address(
        region: '${warehouseData.state ?? ''} ${warehouseData.city ?? ''}',
        detailAddress: warehouseData.address ?? '',
      ),
      remark: '용량: ${warehouseData.capacity}',
    );
    final warehouse = await warehouseService.createWarehouseLocation(warehouseLocation);
    _createdWarehouseIds.add(warehouse.id);
    
    // 3. 장비 생성
    final equipments = <Equipment>[];
    for (int i = 0; i < equipmentCount!; i++) {
      final equipmentData = createSmartEquipmentData(
        companyId: company.id!,
        warehouseLocationId: warehouse.id,
      );
      
      // equipmentService가 Equipment을 받는지 확인 필요
      // 일단 Equipment로 변환
      final equipment = Equipment(
        manufacturer: equipmentData.manufacturer,
        name: equipmentData.modelName ?? '',
        category: equipmentData.category1 ?? '',
        subCategory: equipmentData.category2 ?? '',
        subSubCategory: '',
        serialNumber: equipmentData.serialNumber,
        quantity: 1,
        remark: equipmentData.remark,
      );
      final createdEquipment = await equipmentService.createEquipment(equipment);
      equipments.add(createdEquipment);
      _createdEquipmentIds.add(createdEquipment.id!);
    }
    
    return EquipmentScenarioData(
      company: company,
      warehouse: warehouse,
      equipments: equipments,
    );
  }
  
  /// 사용자 관리 시나리오 데이터 생성
  static Future<UserScenarioData> createUserScenario({
    int? userCount = 10,
  }) async {
    final companyService = GetIt.I<CompanyService>();
    final userService = GetIt.I<UserService>();
    
    // 1. 회사 생성
    final companyData = createSmartCompanyData(
      name: '스마트HR 솔루션',
      companyTypes: [CompanyType.customer],
    );
    
    final company = await companyService.createCompany(companyData);
    _createdCompanyIds.add(company.id!);
    
    // 2. 부서별 사용자 생성
    final users = <User>[];
    final departments = ['개발팀', '디자인팀', '영업팀', '운영팀'];
    
    for (final dept in departments) {
      final deptUserCount = userCount! ~/ departments.length;
      for (int i = 0; i < deptUserCount; i++) {
        final userData = createSmartUserData(
          companyId: company.id!,
          department: dept,
          role: i == 0 ? 'manager' : 'staff', // 첫 번째는 매니저
        );
        
        // userService.createUser는 명명된 파라미터로 호출
        final user = await userService.createUser(
          username: userData.username,
          email: userData.email,
          password: userData.password,
          name: userData.name,
          phone: userData.phone,
          role: userData.role,
          companyId: userData.companyId ?? company.id!,
          branchId: userData.branchId,
        );
        users.add(user);
        _createdUserIds.add(user.id!);
      }
    }
    
    return UserScenarioData(
      company: company,
      users: users,
      departmentGroups: _groupUsersByDepartment(users),
    );
  }
  
  /// 라이선스 관리 시나리오 데이터 생성
  static Future<LicenseScenarioData> createLicenseScenario({
    int? licenseCount = 8,
  }) async {
    final companyService = GetIt.I<CompanyService>();
    final userService = GetIt.I<UserService>();
    final licenseService = GetIt.I<LicenseService>();
    
    // 1. 회사 생성
    final companyData = createSmartCompanyData(
      name: '소프트웨어 라이선스 매니지먼트',
      companyTypes: [CompanyType.partner],
    );
    
    final company = await companyService.createCompany(companyData);
    _createdCompanyIds.add(company.id!);
    
    // 2. 사용자 생성 (라이선스 할당용)
    final users = <User>[];
    for (int i = 0; i < 5; i++) {
      final userData = createSmartUserData(
        companyId: company.id!,
        role: i == 0 ? 'admin' : 'staff',
      );
      
      final user = await userService.createUser(
        username: userData.username,
        email: userData.email,
        password: userData.password,
        name: userData.name,
        phone: userData.phone,
        role: userData.role,
        companyId: userData.companyId ?? company.id!,
        branchId: userData.branchId,
      );
      users.add(user);
      _createdUserIds.add(user.id!);
    }
    
    // 3. 라이선스 생성 (일부는 사용자에게 할당)
    final licenses = <License>[];
    for (int i = 0; i < licenseCount!; i++) {
      final licenseData = createSmartLicenseData(
        companyId: company.id!,
      );
      
      // licenseService.createLicense는 License 객체를 받음
      final license = License(
        licenseKey: licenseData.licenseKey,
        productName: licenseData.productName ?? '',
        vendor: licenseData.vendor ?? '',
        licenseType: licenseData.licenseType ?? '',
        userCount: licenseData.userCount ?? 1,
        purchaseDate: licenseData.purchaseDate,
        expiryDate: licenseData.expiryDate,
        purchasePrice: licenseData.purchasePrice ?? 0.0,
        companyId: licenseData.companyId,
        branchId: licenseData.branchId,
        remark: licenseData.remark,
      );
      final createdLicense = await licenseService.createLicense(license);
      licenses.add(createdLicense);
      _createdLicenseIds.add(createdLicense.id!);
    }
    
    return LicenseScenarioData(
      company: company,
      users: users,
      licenses: licenses,
      assignedLicenses: licenses,
      unassignedLicenses: licenses,
    );
  }
  
  // 데이터 정리 메서드
  
  /// 생성된 모든 테스트 데이터 삭제
  static Future<void> cleanupAllTestData() async {
    final equipmentService = GetIt.I<EquipmentService>();
    final licenseService = GetIt.I<LicenseService>();
    final userService = GetIt.I<UserService>();
    final warehouseService = GetIt.I<WarehouseService>();
    final companyService = GetIt.I<CompanyService>();
    
    // 장비 삭제
    for (final id in _createdEquipmentIds.reversed) {
      await equipmentService.deleteEquipment(id);
    }
    _createdEquipmentIds.clear();
    
    // 라이선스 삭제
    for (final id in _createdLicenseIds.reversed) {
      await licenseService.deleteLicense(id);
    }
    _createdLicenseIds.clear();
    
    // 사용자 삭제
    for (final id in _createdUserIds.reversed) {
      await userService.deleteUser(id);
    }
    _createdUserIds.clear();
    
    // 창고 삭제
    for (final id in _createdWarehouseIds.reversed) {
      await warehouseService.deleteWarehouseLocation(id);
    }
    _createdWarehouseIds.clear();
    
    // 회사 삭제
    for (final id in _createdCompanyIds.reversed) {
      await companyService.deleteCompany(id);
    }
    _createdCompanyIds.clear();
    
    // 캐시 초기화
    _cache.clear();
  }
  
  /// 특정 타입의 데이터만 삭제
  static Future<void> cleanupTestDataByType(TestDataType type) async {
    switch (type) {
      case TestDataType.company:
        final companyService = GetIt.I<CompanyService>();
        for (final id in _createdCompanyIds.reversed) {
          await companyService.deleteCompany(id);
        }
        _createdCompanyIds.clear();
        break;
      case TestDataType.user:
        final userService = GetIt.I<UserService>();
        for (final id in _createdUserIds.reversed) {
          await userService.deleteUser(id);
        }
        _createdUserIds.clear();
        break;
      case TestDataType.equipment:
        final equipmentService = GetIt.I<EquipmentService>();
        for (final id in _createdEquipmentIds.reversed) {
          await equipmentService.deleteEquipment(id);
        }
        _createdEquipmentIds.clear();
        break;
      case TestDataType.license:
        final licenseService = GetIt.I<LicenseService>();
        for (final id in _createdLicenseIds.reversed) {
          await licenseService.deleteLicense(id);
        }
        _createdLicenseIds.clear();
        break;
      case TestDataType.warehouse:
        final warehouseService = GetIt.I<WarehouseService>();
        for (final id in _createdWarehouseIds.reversed) {
          await warehouseService.deleteWarehouseLocation(id);
        }
        _createdWarehouseIds.clear();
        break;
    }
  }
  
  // 헬퍼 메서드
  
  static String _getCategoryDetail(String category) {
    final details = {
      '노트북': '휴대용 컴퓨터',
      '데스크탑': '고정형 컴퓨터',
      '모니터': '디스플레이 장치',
      '프린터': '출력 장치',
      '네트워크장비': '통신 장비',
      '서버': '서버 컴퓨터',
      '태블릿': '태블릿 PC',
      '스캐너': '입력 장치',
    };
    return details[category] ?? '기타';
  }
  
  static double _getRealisticPrice(String category) {
    final basePrices = {
      '노트북': 1500000.0,
      '데스크탑': 1200000.0,
      '모니터': 400000.0,
      '프린터': 300000.0,
      '네트워크장비': 200000.0,
      '서버': 5000000.0,
      '태블릿': 800000.0,
      '스캐너': 250000.0,
    };
    final basePrice = basePrices[category] ?? 500000.0;
    // ±30% 범위의 가격 변동
    return basePrice * (0.7 + _random.nextDouble() * 0.6);
  }
  
  static String _getVendorFromProduct(String productName) {
    if (productName.contains('Microsoft')) return 'Microsoft';
    if (productName.contains('Adobe')) return 'Adobe';
    if (productName.contains('AutoCAD')) return 'Autodesk';
    if (productName.contains('JetBrains')) return 'JetBrains';
    if (productName.contains('Slack')) return 'Slack Technologies';
    if (productName.contains('Zoom')) return 'Zoom Video Communications';
    return 'Unknown Vendor';
  }
  
  static double _getLicensePrice(String productName) {
    final prices = {
      'Microsoft Office 365': 120000.0,
      'Adobe Creative Cloud': 600000.0,
      'AutoCAD 2024': 2400000.0,
      'Windows 11 Pro': 200000.0,
      'Visual Studio Enterprise': 3600000.0,
      'JetBrains All Products': 300000.0,
      'Slack Business+': 180000.0,
      'Zoom Business': 240000.0,
    };
    return prices[productName] ?? 100000.0;
  }
  
  static Map<String, List<User>> _groupUsersByDepartment(List<User> users) {
    final groups = <String, List<User>>{};
    // 실제로는 사용자 모델에 부서 정보가 없으므로, 여기서는 더미 구현
    // 실제 구현시에는 사용자 확장 속성이나 별도 테이블 활용
    return groups;
  }
  
  /// GenerationStrategy를 받아서 테스트 데이터를 생성하는 메서드
  Future<TestData> generate(GenerationStrategy strategy) async {
    final data = await _generateByType(strategy.dataType);
    
    // 필드별 커스터마이징 적용
    if (data is Map<String, dynamic>) {
      for (final field in strategy.fields) {
        data[field.fieldName] = _generateFieldValue(field);
      }
    }
    
    return TestData(
      dataType: strategy.dataType.toString(),
      data: data,
      metadata: {
        'generated': true,
        'timestamp': DateTime.now().toIso8601String(),
      },
    );
  }
  
  /// 타입별 기본 데이터 생성
  static Future<dynamic> _generateByType(Type type) async {
    switch (type.toString()) {
      case 'CreateEquipmentRequest':
        // 기본값 사용 - 실제 사용 시 적절한 값으로 대체 필요
        return createSmartEquipmentData(
          companyId: 1,
          warehouseLocationId: 1,
        );
      case 'CreateCompanyRequest':
        return createSmartCompanyData();
      case 'CreateWarehouseLocationRequest':
        return createSmartWarehouseData();
      case 'CreateLicenseRequest':
        // 기본값 사용 - 실제 사용 시 적절한 값으로 대체 필요
        return createSmartLicenseData(
          companyId: 1,
        );
      default:
        throw Exception('Unsupported type: $type');
    }
  }
  
  /// 필드 생성 전략에 따른 값 생성
  static dynamic _generateFieldValue(FieldGeneration field) {
    switch (field.strategy) {
      case 'unique':
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        return '${field.prefix ?? ''}$timestamp';
      case 'realistic':
        if (field.pool != null && field.pool!.isNotEmpty) {
          return field.pool![_random.nextInt(field.pool!.length)];
        }
        if (field.relatedTo == 'manufacturer') {
          // manufacturer에 따른 모델명 생성
          return _generateRealisticModel(field.fieldName);
        }
        break;
      case 'enum':
        if (field.values != null && field.values!.isNotEmpty) {
          return field.values![_random.nextInt(field.values!.length)];
        }
        break;
      case 'fixed':
        return field.value;
    }
    return null;
  }
  
  static String _generateRealisticModel(String manufacturer) {
    // 간단한 모델명 생성 로직
    final models = _realProductModels[manufacturer];
    if (models != null && models.isNotEmpty) {
      return models[_random.nextInt(models.length)];
    }
    return 'Model-${_random.nextInt(1000)}';
  }
}

// 시나리오 데이터 클래스들

class EquipmentScenarioData {
  final Company company;
  final WarehouseLocation warehouse;
  final List<Equipment> equipments;
  
  EquipmentScenarioData({
    required this.company,
    required this.warehouse,
    required this.equipments,
  });
}

class UserScenarioData {
  final Company company;
  final List<User> users;
  final Map<String, List<User>> departmentGroups;
  
  UserScenarioData({
    required this.company,
    required this.users,
    required this.departmentGroups,
  });
}

class LicenseScenarioData {
  final Company company;
  final List<User> users;
  final List<License> licenses;
  final List<License> assignedLicenses;
  final List<License> unassignedLicenses;
  
  LicenseScenarioData({
    required this.company,
    required this.users,
    required this.licenses,
    required this.assignedLicenses,
    required this.unassignedLicenses,
  });
}

// 테스트 데이터 타입 열거형
enum TestDataType {
  company,
  user,
  equipment,
  license,
  warehouse,
}