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

  OutletRemoteDataProvider(this._apiClient);

  Future<DC<OutletFailure, List<OutletDto>>> fetchOutlets({
    int page = 1,
    int limit = 10,
  }) async {
    try {
      final response = await _apiClient.get(
        '${ApiPath.outlets}/list',
        params: {'page': page, 'limit': limit},
        headers: getAuthorizationHeader(),
      );

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

      final outlets = (response.data['data']['outlets'] as List)
          .map((e) => OutletDto.fromJson(e as Map<String, dynamic>))
          .toList();

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

  Future<DC<OutletFailure, OutletDto>> fetchOutletById(String id) async {
    try {
      final response = await _apiClient.get(
        '${ApiPath.outlets}/detail/$id',
        headers: getAuthorizationHeader(),
      );

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

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

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