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 _logName = 'ProductRemoteDataProvider';

  ProductRemoteDataProvider(this._apiClient);

  Future<DC<ProductFailure, ListProductDto>> fetchProducts({
    int page = 1,
    int limit = 10,
    String? categoryId,
    String? search,
  }) async {
    try {
      Map<String, dynamic> queryParameters = {'page': page, 'limit': limit};

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

      if (search != null && search.isNotEmpty) {
        queryParameters['search'] = search;
      }

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

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

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

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