import 'dart:developer';

import 'package:data_channel/data_channel.dart';
import 'package:injectable/injectable.dart';

import '../../../common/api/api_client.dart';
import '../../../common/api/api_failure.dart';
import '../../../common/function/app_function.dart';
import '../../../common/url/api_path.dart';
import '../../../domain/category/category.dart';
import '../category_dtos.dart';

@injectable
class CategoryRemoteDataProvider {
  final ApiClient _apiClient;
  final _logName = 'CategoryRemoteDataProvider';

  CategoryRemoteDataProvider(this._apiClient);

  Future<DC<CategoryFailure, ListCategoryDto>> fetchCategories({
    int page = 1,
    int limit = 10,
  }) async {
    try {
      final response = await _apiClient.get(
        ApiPath.categories,
        params: {'page': page, 'limit': limit},
        headers: getAuthorizationHeader(),
      );

      if (response.data['data'] == null) {
        return DC.error(const CategoryFailure.empty());
      }

      final categories = ListCategoryDto.fromJson(
        response.data['data'] as Map<String, dynamic>,
      );

      return DC.data(categories);
    } on ApiFailure catch (e, s) {
      log('fetchCategoryError', name: _logName, error: e, stackTrace: s);
      return DC.error(CategoryFailure.serverError(e));
    }
  }
}
