import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/api/api_client.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/request_model/PatientER_RC.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/request_model/RRTRequestModel.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/AmbulanceRequestOrdersModel.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/EROnlineCheckInPaymentDetailsResponse.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/ProjectAvgERWaitingTime.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/RRTServiceData.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/rrt_procedures_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

import 'models/resp_model/PatientERTransportationMethod.dart';

abstract class EmergencyServicesRepo {
  Future<Either<Failure, GenericApiModel<List<RRTProceduresResponseModel>>>> getRRTProcedures(int languageId);

  Future<Either<Failure, GenericApiModel<List<ProjectAvgERWaitingTime>>>> getNearestEr({int? id, int? projectID});

  Future<Either<Failure, GenericApiModel<dynamic>>> checkPatientERAdvanceBalance();

  Future<Either<Failure, GenericApiModel<List<HospitalsModel>>>> getProjectList();

  Future<Either<Failure, GenericApiModel<EROnlineCheckInPaymentDetailsResponse>>> checkPatientERPaymentInformation({int projectID});

  Future<Either<Failure, GenericApiModel<dynamic>>> createAdvancePaymentForER(
      {required int projectID,
      required AuthenticatedUser authUser,
      required num paymentAmount,
      required String paymentMethodName,
      required String paymentReference});

  Future<Either<Failure, GenericApiModel<dynamic>>> addAdvanceNumberRequest(
      {required String advanceNumber, required String paymentReference, required String appointmentNo});

  Future<Either<Failure, GenericApiModel<dynamic>>> getProjectIDFromNFC({required String nfcCode});

  Future<Either<Failure, GenericApiModel<dynamic>>> autoGenerateInvoiceERClinic({required int projectID});

  Future<Either<Failure, GenericApiModel<List<PatientERTransportationMethod>>>> getTransportationMethods({int? id});

  Future<Either<Failure, GenericApiModel<bool>>> submitAmbulanceRequest(PatientER_RC request);

  Future<Either<Failure, GenericApiModel<List<AmbulanceRequestOrdersModel>>>> getTransportationOrders({int? id});

  Future<Either<Failure, GenericApiModel<bool>>>  cancelOrder(int? iD, int patientId);

  Future<Either<Failure, GenericApiModel<bool>>> submitRRTRequest(RRTRequestModel request);

  Future<Either<Failure, GenericApiModel<RRTServiceData>>> getRRTOrders({int? id});

  Future<Either<Failure, GenericApiModel<bool>>> cancelRRTOrder(int? iD);
  Future<Either<Failure, GenericApiModel<String>>> getTermsAndCondition();
}

class EmergencyServicesRepoImp implements EmergencyServicesRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

  EmergencyServicesRepoImp({required this.loggerService, required this.apiClient});

  Future<Either<Failure, GenericApiModel<List<ProjectAvgERWaitingTime>>>> getNearestEr({int? id, int? projectID}) async {
    Map<String, dynamic> mapDevice = {'IsForER': true};

    try {
      GenericApiModel<List<ProjectAvgERWaitingTime>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_NEAREST_HOSPITAL,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_ProjectAvgERWaitingTime'];

            final clinicsList =
                list.map((item) => ProjectAvgERWaitingTime.fromJson(item as Map<String, dynamic>)).toList().cast<ProjectAvgERWaitingTime>();
            apiResponse = GenericApiModel<List<ProjectAvgERWaitingTime>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: clinicsList,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<RRTProceduresResponseModel>>>> getRRTProcedures(int languageId) async {
    Map<String, dynamic> mapDevice = {"ProjectID": 15, "languageID":1};

    try {
      GenericApiModel<List<RRTProceduresResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_RRT_PROCEDURE_LIST,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['Vida_ProcedureList'];
            final proceduresList =
                list.map((item) => RRTProceduresResponseModel.fromJson(item as Map<String, dynamic>)).toList().cast<RRTProceduresResponseModel>();

            apiResponse = GenericApiModel<List<RRTProceduresResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: proceduresList,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<PatientERTransportationMethod>>>> getTransportationMethods({int? id}) async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<List<PatientERTransportationMethod>>? apiResponse;
      Failure? failure;
      await apiClient.get(
        "$GET_ALL_TRANSPORTATIONS_RC?patientID=$id",
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['response']['transportationservices'];
            final proceduresList = list
                .map((item) => PatientERTransportationMethod.fromJson(item as Map<String, dynamic>))
                .toList()
                .cast<PatientERTransportationMethod>();

            apiResponse = GenericApiModel<List<PatientERTransportationMethod>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: proceduresList,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<HospitalsModel>>>> getProjectList() async {
    Map<String, dynamic> request = {"IsEROnlineCheckIn":true,'IsOnlineCheckIn': false, 'IsAdvancePayment': false, 'IsForER': true};

    try {
      GenericApiModel<List<HospitalsModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PROJECT_LIST,
        body: request,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['ListProject'];

            final appointmentsList = list.map((item) => HospitalsModel.fromJson(item as Map<String, dynamic>)).toList().cast<HospitalsModel>();

            apiResponse = GenericApiModel<List<HospitalsModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentsList,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> submitAmbulanceRequest(PatientER_RC request) async {
    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(
        body: request.toJson(),
        INSERT_TRANSPORTATION_ORDER_RC,
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: true,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<AmbulanceRequestOrdersModel>>>> getTransportationOrders({int? id}) async {
    try {
      GenericApiModel<List<AmbulanceRequestOrdersModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        body: {},
        "$GET_ALL_TRANSPORTATIONS_ORDERS?patientID=$id",
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['response'];
            final proceduresList =
                list.map((item) => AmbulanceRequestOrdersModel.fromJson(item as Map<String, dynamic>)).toList().cast<AmbulanceRequestOrdersModel>();

            apiResponse = GenericApiModel<List<AmbulanceRequestOrdersModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: proceduresList,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> cancelOrder(int? iD, int patientID) async {
    try {
      GenericApiModel<bool>? apiResponse;

      Map<String, dynamic> request = {};
      request['Id'] = iD;
      request['StatusId'] = 6;
      request['ClickButton'] = 14;
      request['PatientID'] = patientID;
      Failure? failure;
      await apiClient.post(
        body: request,
        CANCEL_AMBULANCE_REQUEST,
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: true,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> checkPatientERAdvanceBalance() async {
    Map<String, dynamic> mapDevice = {"ClinicID": 10};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        CHECK_PATIENT_ER_ADVANCE_BALANCE,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) => failure = failureType,
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final bool patientHasERBalance = response['BalanceAmount'] > 0;
            log(patientHasERBalance.toString());
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: patientHasERBalance,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<EROnlineCheckInPaymentDetailsResponse>>> checkPatientERPaymentInformation({int? projectID}) async {
    Map<String, dynamic> mapDevice = {"ClinicID": 10, "ProjectID": projectID ?? 0};

    try {
      GenericApiModel<EROnlineCheckInPaymentDetailsResponse>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_ER_ONLINE_PAYMENT_DETAILS,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final erOnlineCheckInPaymentDetailsResponse = EROnlineCheckInPaymentDetailsResponse.fromJson(response["ResponsePatientShare"]);
            apiResponse = GenericApiModel<EROnlineCheckInPaymentDetailsResponse>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: erOnlineCheckInPaymentDetailsResponse,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> createAdvancePaymentForER(
      {required int projectID,
      required AuthenticatedUser authUser,
      required num paymentAmount,
      required String paymentMethodName,
      required String paymentReference}) async {
    Map<String, dynamic> mapDevice = {
      "LanguageID": 1,
      "ERAdvanceAmount": {
        "ProjectId": projectID,
        "PatientId": authUser.patientId,
        "ClinicId": 10,
        "DepositorName": "${authUser.firstName!} ${authUser.lastName!}",
        "MemberId": authUser.patientId,
        "NationalityID": authUser.nationalityId,
        "PaymentAmount": paymentAmount,
        "PaymentDate": DateUtil.convertDateToString(DateTime.now()),
        "PaymentMethodName": paymentMethodName,
        "PaymentReferenceNumber": paymentReference,
        "SourceType": 2
      }
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ER_CREATE_ADVANCE_PAYMENT,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final vidaAdvanceNumber = response['ER_AdvancePaymentResponse']['AdvanceNumber'].toString();
            log(vidaAdvanceNumber);
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: vidaAdvanceNumber,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> addAdvanceNumberRequest(
      {required String advanceNumber, required String paymentReference, required String appointmentNo}) async {
    Map<String, dynamic> requestBody = {
      "AdvanceNumber": advanceNumber,
      "AdvanceNumber_VP": advanceNumber,
      "PaymentReferenceNumber": paymentReference,
      "AppointmentID": appointmentNo,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ADD_ADVANCE_NUMBER_REQUEST,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: response,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> getProjectIDFromNFC({required String nfcCode}) async {
    Map<String, dynamic> mapDevice = {"nFC_Code": nfcCode};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PROJECT_FROM_NFC,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final projectID = response['GetProjectByNFC'][0]["ProjectID"];
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: projectID,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> autoGenerateInvoiceERClinic({required int projectID}) async {
    Map<String, dynamic> mapDevice = {
      "ProjectID": projectID,
      "ClinicID": "10",
      "IsAdvanceAvailable": true,
      "MemberID": 102,
      "PaymentMethod": "VISA",
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        AUTO_GENERATE_INVOICE_ER,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: true,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> submitRRTRequest(RRTRequestModel request) async {
    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(
        body: request.toJson(),
        ADD_RRT_ORDER_RC,
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: true,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> cancelRRTOrder(int? iD) async{
    try {
      GenericApiModel<bool>? apiResponse;

      Map<String, dynamic> request = {"Id": iD, "ClickButton": 14};

      Failure? failure;
      await apiClient.post(
        body: request,
        UPDATE_RRT_ORDER_RC,
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: true,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }

  }

  @override
  Future<Either<Failure, GenericApiModel<RRTServiceData>>> getRRTOrders({int? id}) async {
    try {
      GenericApiModel<RRTServiceData>? apiResponse;
      Failure? failure;
      await apiClient.post(
        body: {},
        GET_ALL_RRT_ORDERS_RC,
        isRCService: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['response'];

            RRTServiceData serviceData = RRTServiceData();
            list.forEach((item) {
              if (item["StatusId"] == 1 || item["StatusId"] == 2) {
                // Pending
                serviceData.pendingOrders.add(GetCMCAllOrdersResponseModel.fromJson(item));
              }
              serviceData.completedOrders.add(GetCMCAllOrdersResponseModel.fromJson(item));
            });

            apiResponse = GenericApiModel<RRTServiceData>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: serviceData,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<String>>> getTermsAndCondition() async {
    try {
      GenericApiModel<String>? apiResponse;
      Failure? failure;
      await apiClient.post(
        body: {},
        GET_USER_TERMS,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final agreement = response['UserAgreementContent'];
            apiResponse = GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: agreement,
            );

          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }

  }


}
