import 'package:proxibuy/core/services/api/api_routes.dart';
import 'package:proxibuy/core/services/api/api_service.dart';
import 'package:proxibuy/core/services/api/response_model.dart';
import 'package:proxibuy/data/models/categories/categories_model.dart';

class CategoryRepository {
  static Future<ResponseModel<List<CategoriesModel>>> fetchAll(
      {int page = 1}) async {
    try {
      var response = await apiService.get('${ApiRoutes.category}?page=$page');
      final res = ResponseModel<List<CategoriesModel>>.fromJson(
        response,
        (data) {
          return (data as List)
              .map((item) => CategoriesModel.fromJson(item))
              .toList();
        },
      );
      return res;
    } catch (e) {
      print("Error: $e");
      rethrow;
    }
  }

  static Future<ResponseModel<List<CategoriesModel>>> fetchAllChild(
      {int page = 1, required final String id}) async {
    try {
      var response = await apiService
          .get('${ApiRoutes.category}?page=$page?filter.parent_id=$id');
      final res = ResponseModel<List<CategoriesModel>>.fromJson(
        response,
        (data) {
          return (data as List)
              .map((item) => CategoriesModel.fromJson(item))
              .toList();
        },
      );
      return res;
    } catch (e) {
      print("Error: $e");
      rethrow;
    }
  }

  static Future<CategoriesModel> fetchOne({required final String id}) async {
    try {
      var response = await apiService.get('${ApiRoutes.category}/$id');
      return CategoriesModel.fromJson(response['category']);
    } catch (e) {
      print("Error: $e");
      rethrow;
    }
  }
}
