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

  CustomerRemoteDataProvider(this._apiClient);

  Future<DC<CustomerFailure, ListCustomerDto>> fetchCustomers({
    int page = 1,
    int limit = 10,
  }) async {
    try {
      final response = await _apiClient.get(
        ApiPath.customers,
        params: {'page': page, 'limit': limit},
        headers: getAuthorizationHeader(),
      );

      if (response.data['success'] == false) {
        return DC.error(const CustomerFailure.unexpectedError());
      }

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

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