import 'package:cargocalculaterapp/features/calculator/data/model/calculate_price_response.dart';
import 'package:cargocalculaterapp/features/calculator/data/model/price_calculate_request.dart';
import 'package:dio/dio.dart';
import '../../../../constants/constants.dart';
import '../../../../core/error/exceptions.dart';
import '../../../../core/local_source/local_source.dart';
import '../../../../injector_container.dart';
import '../model/lead_create_response.dart';
import '../model/lead_create_request.dart';
import 'calculator_remote_data_source.dart';

class CalculatorRemoteDataSourceImpl extends CalculatorRemoteDataSource {
  final Dio dio;

  CalculatorRemoteDataSourceImpl(this.dio);

  @override
  Future<CalculatePriceResponse> priceCalculate(
    PriceCalculateRequest request,
  ) async {
    try {
      final Response response = await dio.post(
        Constants.baseUrl + Urls.calculatePrice,
        options:
            DioConstants.options
              ..headers = {
                "Authorization": "Bearer ${sl<LocalSource>().getAccessToken()}",
              },
        data: request,
      );
      if (response.statusCode == 200 || response.statusCode == 201) {
        return CalculatePriceResponse.fromJson(response.data);
      }
      throw ServerException.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException.fromJson(e.response?.data);
    } on FormatException {
      throw ServerException(message: Validations.someThingWentWrong);
    }
  }

  @override
  Future<LeadCreateResponse> createLead(LeadCreateRequest request) async {
    try {
      final Response response = await dio.post(
        Constants.baseUrl + Urls.lead,
        options:
            DioConstants.options
              ..headers = {
                "Authorization": "Bearer ${sl<LocalSource>().getAccessToken()}",
              },
        data: request,
      );
      if (response.statusCode == 200 || response.statusCode == 201) {
        return LeadCreateResponse.fromJson(response.data);
      }
      throw ServerException.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException.fromJson(e.response?.data);
    } on FormatException {
      throw ServerException(message: Validations.someThingWentWrong);
    }
  }
}
