import 'package:dio/dio.dart';
import 'package:pmu/data/dtos/food_dto.dart';
import 'package:pmu/data/mappers/foods_mapper.dart';
import 'package:pmu/data/repository/api_interface.dart';
import 'package:pmu/domain/models/card.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

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

  static const String _baseUrl = 'https://www.themealdb.com/api/json/v1/1';
  @override
  Future<List<MarketData>?> loadData({OnErrorCallback? onError, String? q}) async {
    try {
      final String url = q != null ? '$_baseUrl/search.php' : '$_baseUrl/filter.php?i=chicken_breast';

      final Response<dynamic> response = await _dio.get(
        url,
        queryParameters: q != null ? {'s': q} : null,
      );

      final FoodsDto dto = FoodsDto.fromJson(response.data as Map<String, dynamic>);
      final List<MarketData>? items = dto.meals?.map((e) => e.toDomain()).toList();
      return items;
    } on DioException catch (e) {
      onError?.call(e.error?.toString());
      return null;
    }
  }
}