import 'package:flutter_app/data/mappers/characters_mapper.dart';
import 'package:dio/dio.dart';
import 'package:flutter_app/domain/models/home.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../../domain/models/card.dart';
import '../dtos/characters_dto.dart';
import 'api_interface.dart';

class GotRepository extends ApiInterface {
  static final Dio _dio = Dio()
    ..interceptors.add(PrettyDioLogger(
      requestHeader: true,
      requestBody: true
    ));
  static const String _baseURL = 'https://api-lyrn.onrender.com';

  @override
  Future<HomeData?> loadData({
    OnErrorCallback? onError,
    String q = '',
    int page = 1,
    int pageSize = 26,
  }) async {
    try {
      const String url = '$_baseURL/characters';

      Response<dynamic> response = await _dio.get<Map<String, dynamic>>(
        url,
        queryParameters: {
          'fullName': q != '' ? q : null,
          'page': page,
          'size': pageSize,
        },
      );
      final CharactersDto dto = CharactersDto.fromJson(response.data);
      final HomeData data = dto.toDomain();
      return data;
    } on DioException catch (e) {
      onError?.call(e.error?.toString());
      return null;
    }
  }
}