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<Pokemon> 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<String, dynamic>;
    return PokemonDto.fromTyradexJson(json, fallbackId: id);
  }

  Future<List<Pokemon>> 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<dynamic> jsonList = jsonDecode(response.body);
    final result = <Pokemon>[];
    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<String, dynamic>));
      } catch (e, st) {
        AppLogger.error('Parsing pokemon échoué: ${json['name']}', e, st);
      }
    }
    return result;
  }
}
