import 'dart:convert'; import 'package:http/http.dart' as http; import '../../core/config/app_constants.dart'; import '../../core/logger.dart'; import '../../domain/entities/pokemon.dart'; import '../dto/pokemon_dto.dart'; /// Accès distant à l'API Tyradex. class PokemonRemoteDataSource { final http.Client _client; PokemonRemoteDataSource({http.Client? client}) : _client = client ?? http.Client(); Future getById(int id) async { AppLogger.info('API: fetching Pokémon $id'); final response = await _client .get(Uri.https(AppConstants.apiBaseUrl, '${AppConstants.apiPokemonPath}/$id')); if (response.statusCode != 200) { throw Exception( 'Erreur récupération du pokémon $id, code ${response.statusCode}'); } final json = jsonDecode(response.body) as Map; return PokemonDto.fromTyradexJson(json, fallbackId: id); } Future> getAll() async { AppLogger.info('API: fetching ALL Pokémon'); final response = await _client .get(Uri.https(AppConstants.apiBaseUrl, AppConstants.apiPokemonPath)); if (response.statusCode != 200) { throw Exception('Failed to load pokemon (code ${response.statusCode})'); } final List jsonList = jsonDecode(response.body); final result = []; for (final json in jsonList) { if (json['pokedex_id'] == 0) continue; // entrée générique Tyradex try { result.add(PokemonDto.fromTyradexJson(json as Map)); } catch (e, st) { AppLogger.error('Parsing pokemon échoué: ${json['name']}', e, st); } } return result; } }