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/customer/customer.dart';
import '../customer_dtos.dart';

@injectable
class CustomerRemoteDataProvider {
  final ApiClient _apiClient;
  final String _logName = "CustomerRemoteDataProvider";

  CustomerRemoteDataProvider(this._apiClient);

  Future<DC<CustomerFailure, List<CustomerDto>>> fetch({
    int page = 1,
    int limit = 20,
    String? search,
  }) async {
    try {
      Map<String, dynamic> params = {'page': page, 'limit': limit};

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

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

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

      final dto = (response.data['data']['data'] as List)
          .map((e) => CustomerDto.fromJson(e))
          .toList();

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