import 'package:em2rp/services/api_service.dart';
import 'package:em2rp/utils/debug_log.dart';

/// Repository pour gérer toutes les opérations sur les conteneurs.
class ContainerRepository {
  final ApiService _apiService;

  ContainerRepository(this._apiService);

  /// Récupère tous les conteneurs
  Future<List<Map<String, dynamic>>> getContainers() async {
    try {
      final result = await _apiService.call('getContainers', {});
      final containers = result['containers'] as List<dynamic>?;
      if (containers == null) return [];
      return containers.map((e) => e as Map<String, dynamic>).toList();
    } catch (e) {
      throw Exception('Erreur lors de la récupération des conteneurs: $e');
    }
  }

  /// Récupère plusieurs containers par leurs IDs
  Future<List<Map<String, dynamic>>> getContainersByIds(
      List<String> containerIds) async {
    try {
      if (containerIds.isEmpty) return [];

      print(
          '[ContainerRepository] Getting containers by IDs: ${containerIds.length} items');
      final result = await _apiService.call('getContainersByIds', {
        'containerIds': containerIds,
      });
      final containers = result['containers'] as List<dynamic>?;
      if (containers == null) {
        print('[ContainerRepository] No containers in result');
        return [];
      }
      print('[ContainerRepository] Found ${containers.length} containers by IDs');
      return containers.map((e) => e as Map<String, dynamic>).toList();
    } catch (e) {
      print('[ContainerRepository] Error getting containers by IDs: $e');
      throw Exception('Erreur lors de la récupération des containers: $e');
    }
  }

  /// Récupère les containers avec pagination et filtrage
  Future<Map<String, dynamic>> getContainersPaginated({
    int limit = 20,
    String? startAfter,
    String? type,
    String? status,
    String? searchQuery,
    String? category,
    String sortBy = 'id',
    String sortOrder = 'asc',
  }) async {
    try {
      final params = <String, dynamic>{
        'limit': limit,
        'sortBy': sortBy,
        'sortOrder': sortOrder,
      };

      if (startAfter != null) params['startAfter'] = startAfter;
      if (type != null) params['type'] = type;
      if (status != null) params['status'] = status;
      if (category != null) params['category'] = category;
      if (searchQuery != null && searchQuery.isNotEmpty) {
        params['searchQuery'] = searchQuery;
      }

      final result =
          await (_apiService as FirebaseFunctionsApiService).callPaginated(
        'getContainersPaginated',
        params,
      );

      return {
        'containers': (result['containers'] as List<dynamic>?)
                ?.map((e) => e as Map<String, dynamic>)
                .toList() ??
            [],
        'hasMore': result['hasMore'] as bool? ?? false,
        'lastVisible': result['lastVisible'] as String?,
        'total': result['total'] as int? ?? 0,
      };
    } catch (e) {
      DebugLog.error('[ContainerRepository] Error in getContainersPaginated', e);
      throw Exception(
          'Erreur lors de la récupération paginée des containers: $e');
    }
  }

  /// Récupère les containers contenant un équipement
  Future<List<Map<String, dynamic>>> getContainersByEquipment(
      String equipmentId) async {
    try {
      final result = await _apiService.call('getContainersByEquipment', {
        'equipmentId': equipmentId,
      });
      final containers = result['containers'] as List<dynamic>?;
      if (containers == null) return [];
      return containers.map((e) => e as Map<String, dynamic>).toList();
    } catch (e) {
      throw Exception('Erreur lors de la récupération des containers: $e');
    }
  }

  /// Vérifie la disponibilité d'un container
  Future<Map<String, dynamic>> checkContainerAvailability({
    required String containerId,
    required DateTime startDate,
    required DateTime endDate,
    String? excludeEventId,
  }) async {
    try {
      final result = await _apiService.call('checkContainerAvailability', {
        'containerId': containerId,
        'startDate': startDate.toIso8601String(),
        'endDate': endDate.toIso8601String(),
        if (excludeEventId != null) 'excludeEventId': excludeEventId,
      });
      return result;
    } catch (e) {
      throw Exception('Erreur lors de la vérification de disponibilité du container: $e');
    }
  }
}
