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<List<Pokemon>> 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<Pokemon?> 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<void> saveAll(List<Pokemon> pokemons) async =>
      local?.saveAll(pokemons);

  @override
  Future<void> update(Pokemon pokemon) async => local?.update(pokemon);

  @override
  Future<int> caughtCount() async => (await local?.caughtCount()) ?? 0;

  @override
  Future<int> seenCount() async => (await local?.seenCount()) ?? 0;
}
