import 'package:dio/dio.dart';
import 'package:first_project/data/dtos/anime_dto.dart';
import 'package:first_project/data/mappers/anime_mapper.dart';
import 'package:first_project/data/repositories/api_interface.dart';
import 'package:first_project/domain/models/home.dart';
import 'package:first_project/presentation/home_page/home_page.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class AnimeRepository extends ApiInterface {
  static final Dio _dio = Dio()
    ..interceptors.add(PrettyDioLogger(
      requestHeader: true,
      requestBody: true,
    ));

  static const String _baseUrl = 'https://api.jikan.moe';

  @override
  Future<HomeData?> loadData(
      {OnErrorCallback? onError, String? q, int page = 1, int pageSize = 25}) async {
    try {
      const String url = '$_baseUrl/v4/anime';
      Map<String, dynamic> query = {'q': q, 'page': page, 'limit': pageSize};
      final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
        url,
        queryParameters: query,
      );
      final AnimesDto dto = AnimesDto.fromJson(response.data as Map<String, dynamic>);
      final HomeData data = dto.toDomain();
      return data;
    } on DioException catch (e) {
      onError?.call(e.error?.toString());
      return null;
    }
  }
}
