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/outlet/outlet.dart';
import '../outlet_dtos.dart';

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

  OutletRemoteDataProvider(this._apiClient);

  Future<DC<OutletFailure, OutletDto>> fetchById({required outletId}) async {
    try {
      final response = await _apiClient.get(
        '${ApiPath.outlet}/detail/$outletId',
        headers: getAuthorizationHeader(),
      );

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

      final dto = OutletDto.fromJson(response.data['data']);

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

  Future<DC<OutletFailure, List<OutletDto>>> fetchList({
    int page = 1,
    int limit = 10,
    String? search,
    bool? isActive,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'page': page,
        'limit': limit,
        'search': search ?? 'null',
        'is_active': isActive != null ? isActive.toString() : 'null',
      };

      final response = await _apiClient.get(
        '${ApiPath.outlet}/list',
        params: params,
        headers: getAuthorizationHeader(),
      );

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

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

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