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/extension/extension.dart';
import '../../../common/function/app_function.dart';
import '../../../common/url/api_path.dart';
import '../../../domain/order/order.dart';
import '../order_dtos.dart';

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

  OrderRemoteDataProvider(this._apiClient);

  Future<DC<OrderFailure, List<OrderDto>>> fetch({
    int page = 1,
    int limit = 10,
    String? status,
    String? search,
    String? outletId,
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    try {
      Map<String, dynamic> params = {
        'page': page,
        'limit': limit,
        'date_from': dateFrom.toServerDate,
        'date_to': dateTo.toServerDate,
      };

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

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

      // if (outletId != null) {
      //   params['outlet_id'] = outletId;
      // }

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

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

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

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