import 'package:get_it/get_it.dart';
import 'package:superport/core/constants/app_constants.dart';
import 'package:superport/services/auth_service.dart';
import 'package:superport/services/equipment_service.dart';
import 'package:superport/services/warehouse_service.dart';
import 'package:superport/services/company_service.dart';
import 'package:superport/core/utils/debug_logger.dart';
import 'package:superport/models/company_model.dart';

/// API 상태 테스트 서비스
class HealthTestService {
  final AuthService _authService = GetIt.instance<AuthService>();
  final EquipmentService _equipmentService = GetIt.instance<EquipmentService>();
  final WarehouseService _warehouseService = GetIt.instance<WarehouseService>();
  final CompanyService _companyService = GetIt.instance<CompanyService>();
  
  /// 모든 주요 API 엔드포인트 테스트
  Future<Map<String, dynamic>> checkAllEndpoints() async {
    final results = <String, dynamic>{};
    
    // 1. 인증 상태 확인
    try {
      final isAuthenticated = await _authService.isLoggedIn();
      final accessToken = await _authService.getAccessToken();
      final refreshToken = await _authService.getRefreshToken();
      
      results['auth'] = {
        'success': isAuthenticated,
        'accessToken': accessToken != null,
        'refreshToken': refreshToken != null,
      };
      DebugLogger.log('인증 상태', tag: 'HEALTH_TEST', data: results['auth']);
    } catch (e) {
      results['auth'] = {'success': false, 'error': e.toString()};
    }
    
    // 2. 장비 API 체크
    try {
      DebugLogger.log('장비 API 체크 시작', tag: 'HEALTH_TEST');
      
      final equipments = await _equipmentService.getEquipments(page: 1, perPage: AppConstants.smallPageSize);
      results['equipments'] = {
        'success': true,
        'count': equipments.items.length,
        'sample': equipments.items.take(2).map((e) => {
          'id': e.id,
          'name': e.serialNumber,
          'manufacturer': e.vendorName ?? 'Unknown',
          'category': e.modelName ?? 'Unknown',
        }).toList(),
      };
      
      DebugLogger.log('장비 API 결과', tag: 'HEALTH_TEST', data: results['equipments']);
    } catch (e) {
      results['equipments'] = {'success': false, 'error': e.toString()};
    }
    
    // 3. 입고지 API 체크
    try {
      DebugLogger.log('입고지 API 체크 시작', tag: 'HEALTH_TEST');
      
      final warehousesResponse = await _warehouseService.getWarehouseLocations();
      results['warehouses'] = {
        'success': true,
        'count': warehousesResponse.items.length,
        'sample': warehousesResponse.items.take(2).map((w) => {
          'id': w.id,
          'name': w.name,
          'address': w.address.toString(),
        }).toList(),
      };
      
      DebugLogger.log('입고지 API 결과', tag: 'HEALTH_TEST', data: results['warehouses']);
    } catch (e) {
      results['warehouses'] = {'success': false, 'error': e.toString()};
    }
    
    // 4. 회사 API 체크
    try {
      DebugLogger.log('회사 API 체크 시작', tag: 'HEALTH_TEST');
      
      final companiesResponse = await _companyService.getCompanies();
      results['companies'] = {
        'success': true,
        'count': companiesResponse.items.length,
        'sample': companiesResponse.items.take(2).map((c) => {
          'id': c.id,
          'name': c.name,
          'companyTypes': c.companyTypes.map((t) => companyTypeToString(t)).toList(),
        }).toList(),
      };
      
      DebugLogger.log('회사 API 결과', tag: 'HEALTH_TEST', data: results['companies']);
    } catch (e) {
      results['companies'] = {'success': false, 'error': e.toString()};
    }
    
    return results;
  }
  
  /// 특정 엔드포인트만 체크
  Future<Map<String, dynamic>> checkEndpoint(String endpoint) async {
    switch (endpoint) {
      case 'equipments':
        try {
          final equipments = await _equipmentService.getEquipments(page: 1, perPage: AppConstants.defaultPageSize);
          return {
            'success': true,
            'count': equipments.items.length,
            'data': equipments.items.map((e) => e.toJson()).toList(),
          };
        } catch (e) {
          return {'success': false, 'error': e.toString()};
        }
        
      case 'warehouses':
        try {
          final warehousesResponse = await _warehouseService.getWarehouseLocations();
          return {
            'success': true,
            'count': warehousesResponse.items.length,
            'data': warehousesResponse.items.map((w) => {
              'id': w.id,
              'name': w.name,
              'address': w.address.toString(),
              'remark': w.remark,
            }).toList(),
          };
        } catch (e) {
          return {'success': false, 'error': e.toString()};
        }
        
      case 'companies':
        try {
          final companies = await _companyService.getCompanies();
          return {
            'success': true,
            'count': companies.items.length,
            'data': companies.items.map((c) => c.toJson()).toList(),
          };
        } catch (e) {
          return {'success': false, 'error': e.toString()};
        }
        
      default:
        return {'success': false, 'error': 'Unknown endpoint: $endpoint'};
    }
  }
}