import '../../core/config/app_constants.dart'; import '../../core/logger.dart'; import '../../domain/entities/pokemon.dart'; import '../../domain/repositories/pokemon_repository.dart'; import '../datasources/pokemon_local_datasource.dart'; import '../datasources/pokemon_remote_datasource.dart'; /// Implémentation : DB locale d'abord, complétée/repliée sur l'API. /// [local] vaut `null` sur le web (pas de SQLite). class PokemonRepositoryImpl implements PokemonRepository { final PokemonRemoteDataSource remote; final PokemonLocalDataSource? local; PokemonRepositoryImpl({required this.remote, this.local}); @override Future> getAll() async { final localDs = local; if (localDs == null) return remote.getAll(); final cached = await localDs.getAll(); if (cached.length >= AppConstants.totalPokemon) return cached; try { final remoteList = await remote.getAll(); await localDs.saveAll(remoteList); return localDs.getAll(); } catch (e, st) { AppLogger.error('Sync getAll échouée', e, st); return cached; } } @override Future getById(int id) async { final localDs = local; if (localDs != null) { final cached = await localDs.getById(id); if (cached != null) return cached; } try { final fetched = await remote.getById(id); if (localDs != null) await localDs.saveAll([fetched]); return fetched; } catch (e, st) { AppLogger.error('getById($id) échoué', e, st); return null; } } @override Future saveAll(List pokemons) async => local?.saveAll(pokemons); @override Future update(Pokemon pokemon) async => local?.update(pokemon); @override Future caughtCount() async => (await local?.caughtCount()) ?? 0; @override Future seenCount() async => (await local?.seenCount()) ?? 0; }