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/product/product.dart';
import '../product_dtos.dart';

@injectable
class ProductRemoteDataProvider {
  final ApiClient _apiClient;
  final String _logName = 'ProductRemoteDataProvider';

  ProductRemoteDataProvider(this._apiClient);

  Future<DC<ProductFailure, List<ProductDto>>> fetch({
    int page = 1,
    int limit = 10,
    String? categoryId,
    String? search,
  }) async {
    try {
      Map<String, dynamic> params = {'page': page, 'limit': limit};

      if (categoryId != null) {
        params['category_id'] = categoryId;
      }

      if (search != null) {
        params['search'] = search;
      }

      final response = await _apiClient.get(
        ApiPath.product,
        params: params,
        headers: getAuthorizationHeader(),
      );

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

      final dto = (response.data['data']['products'] as List)
          .map((item) => ProductDto.fromJson(item))
          .toList();

      return DC.data(dto);
    } on ApiFailure catch (e, s) {
      log('fetchProductError', name: _logName, error: e, stackTrace: s);
      return DC.error(ProductFailure.serverError(e));
    }
  }
}
