import 'dart:convert';
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/features/symptoms_checker/models/req_models/schedule_appointment_request_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/explanations_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/get_clinic_details_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/rationale_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/schedule_appointment_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_level_response_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class SymptomsCheckerRepo {
  Future<Either<Failure, GenericApiModel<SymptomsUserDetailsResponseModel>>> getUserDetails({
    required String userName,
    required String password,
    String? fileNo,
  });

  Future<Either<Failure, GenericApiModel<BodySymptomResponseModel>>> getBodySymptomsByName({
    required List<String> organNames,
    required String userSessionToken,
    required int gender,
  });

  Future<Either<Failure, GenericApiModel<RiskAndSuggestionsResponseModel>>> getRiskFactors({
    required int age,
    required int gender,
    required List<String> evidenceIds,
    required String language,
    required String userSessionToken,
    required String sessionId,
  });

  Future<Either<Failure, GenericApiModel<RiskAndSuggestionsResponseModel>>> getSuggestions({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidenceList,
    required String language,
    required String userSessionToken,
    required String sessionId,
  });

  Future<Either<Failure, GenericApiModel<TriageDataDetails>>> getDiagnosisForTriage({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> initialEvidenceList,
    List<Map<String, String>>? triageEvidence,
    required String language,
    required String userSessionToken,
    required String sessionId,
  });

  Future<Either<Failure, GenericApiModel<List<GetClinicDetailsResponseModel>>>> getClinicDetails({
    required String categoryName,
    required String language,
    required String userSessionToken,
  });

  Future<Either<Failure, GenericApiModel<ScheduleAppointmentResponseModel>>> saveAppointmentDetailsForSymptomsChecker({
    required ScheduleAppointmentRequestModel request,
    required String userSessionToken,
  });

  Future<Either<Failure, GenericApiModel<RationaleResponseModel>>> getRationale({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String generalId,
    required String userSessionToken,
  });

  Future<Either<Failure, GenericApiModel<TriageLevelResponseModel>>> getTriage({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String generalId,
    required String userSessionToken,
  });

  Future<Either<Failure, GenericApiModel<ExplanationsResponseModel>>> getExplanations({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String target,
    required String generalId,
    required String userSessionToken,
  });
}

class SymptomsCheckerRepoImp implements SymptomsCheckerRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<SymptomsUserDetailsResponseModel>>> getUserDetails({
    required String userName,
    required String password,
    String? fileNo,
  }) async {
    Map<String, dynamic> body = {
      "userName": userName,
      "password": password,
    };

    // Add fileNo only if provided (user is logged in)
    if (fileNo != null && fileNo.isNotEmpty) {
      body["fileNo"] = fileNo;
    }

    try {
      GenericApiModel<SymptomsUserDetailsResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.symptomsUserLogin,
        body: body,
        isExternal: true,
        isAllowAny: true,
        isBodyPlainText: false,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("getUserDetails API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // Parse response if it's a string
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            SymptomsUserDetailsResponseModel symptomsUserDetailsResponseModel = SymptomsUserDetailsResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<SymptomsUserDetailsResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: symptomsUserDetailsResponseModel,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing getUserDetails response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getUserDetails: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<BodySymptomResponseModel>>> getBodySymptomsByName({
    required List<String> organNames,
    required String userSessionToken,
    required int gender,
  }) async {
    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };
    Map<String, dynamic> body = {
      'bodyPartName': organNames,
      'gender': gender,
    };

    try {
      GenericApiModel<BodySymptomResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getBodySymptomsByName,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        isBodyPlainText: false,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            BodySymptomResponseModel bodySymptomResponse = BodySymptomResponseModel.fromJson(response);

            apiResponse = GenericApiModel<BodySymptomResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: bodySymptomResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetBodySymptomsByName response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getBodySymptomsByName: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<RiskAndSuggestionsResponseModel>>> getRiskFactors({
    required int age,
    required int gender,
    required List<String> evidenceIds,
    required String language,
    required String userSessionToken,
    required String sessionId,
  }) async {
    // Build evidence list with "initial" source for symptoms
    final List<Map<String, dynamic>> evidenceList = evidenceIds.map((id) {
      return {
        "id": id,
        "source": "initial",
      };
    }).toList();

    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidenceList,
      "language": language,
      "generalId": sessionId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<RiskAndSuggestionsResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getRiskFactors,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("GetRiskFactors API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // Parse response if it's a string
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            RiskAndSuggestionsResponseModel riskFactorsResponse = RiskAndSuggestionsResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<RiskAndSuggestionsResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: riskFactorsResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetRiskFactors response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getRiskFactors: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<TriageDataDetails>>> getDiagnosisForTriage({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> initialEvidenceList,
    List<Map<String, String>>? triageEvidence, // Additional triage-specific evidence
    required String language,
    required String userSessionToken,
    required String sessionId,
  }) async {
    // Build evidence list: combine initial evidence (with sources) with triage evidence
    List<Map<String, dynamic>> evidenceList = [];

    // Add initial evidence (already has sources: initial, red_flags, suggest)
    evidenceList.addAll(initialEvidenceList);

    // Add triage evidence with proper format (id, choice_id, source=triage)
    if (triageEvidence != null && triageEvidence.isNotEmpty) {
      evidenceList.addAll(triageEvidence);
    }

    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidenceList,
      "language": language,
      "suggest_method": "diagnosis",
      "generalId": sessionId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<TriageDataDetails>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.diagnosis,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("getDiagnosisForTriage API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // Parse response if it's a string
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            final updatedResponseData = responseData['dataDetails'];

            TriageDataDetails riskFactorsResponse = TriageDataDetails.fromJson(updatedResponseData);

            apiResponse = GenericApiModel<TriageDataDetails>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: riskFactorsResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing getDiagnosisForTriage response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getDiagnosisForTriage: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<RiskAndSuggestionsResponseModel>>> getSuggestions({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidenceList,
    required String language,
    required String userSessionToken,
    required String sessionId,
  }) async {
    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidenceList,
      "language": language,
      "generalId": sessionId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<RiskAndSuggestionsResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getSuggestions,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("GetSuggestions API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // Parse response if it's a string
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            RiskAndSuggestionsResponseModel riskFactorsResponse = RiskAndSuggestionsResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<RiskAndSuggestionsResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: riskFactorsResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetSuggestions response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getSuggestions: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<GetClinicDetailsResponseModel>>>> getClinicDetails({
    required String categoryName,
    required String language,
    required String userSessionToken,
  }) async {
    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<List<GetClinicDetailsResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.get(
        "${ApiConsts.getClinicFromCondition}$categoryName&language=$language",
        apiHeaders: headers,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          log("response['dataDetails']: ${response['dataDetails']}");
          final clinicDetails;
          try {
            final list = response['dataDetails'];
            clinicDetails = list
                .map((item) => GetClinicDetailsResponseModel.fromJson(item as Map<String, dynamic>))
                .toList()
                .cast<GetClinicDetailsResponseModel>();

            apiResponse = GenericApiModel<List<GetClinicDetailsResponseModel>>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: clinicDetails,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetClinicsByCondition response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in GetClinicsByCondition: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<ScheduleAppointmentResponseModel>>> saveAppointmentDetailsForSymptomsChecker({
    required ScheduleAppointmentRequestModel request,
    required String userSessionToken,
  }) async {
    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    final body = request.toJson();

    try {
      GenericApiModel<ScheduleAppointmentResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.symptomsCheckerScheduleAppointment,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("ScheduleAppointment API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // Parse response if it's a string
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            ScheduleAppointmentResponseModel scheduleAppointmentResponse = ScheduleAppointmentResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<ScheduleAppointmentResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: scheduleAppointmentResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing ScheduleAppointment response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in scheduleAppointment: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<RationaleResponseModel>>> getRationale({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String generalId,
    required String userSessionToken,
  }) async {
    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidence,
      "language": language,
      "generalId": generalId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<RationaleResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getRationale,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("GetRationale API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            RationaleResponseModel rationaleResponse = RationaleResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<RationaleResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: rationaleResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetRationale response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getRationale: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<TriageLevelResponseModel>>> getTriage({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String generalId,
    required String userSessionToken,
  }) async {
    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidence,
      "language": language,
      "generalId": generalId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<TriageLevelResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getTriage,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("GetTriage API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            TriageLevelResponseModel triageResponse = TriageLevelResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<TriageLevelResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: triageResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetTriage response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getTriage: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<ExplanationsResponseModel>>> getExplanations({
    required int age,
    required int gender,
    required List<Map<String, dynamic>> evidence,
    required String language,
    required String target,
    required String generalId,
    required String userSessionToken,
  }) async {
    final Map<String, dynamic> body = {
      "age": {
        "value": age,
      },
      "gender": gender,
      "evidence": evidence,
      "language": language,
      "target": target,
      "generalId": generalId,
    };

    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $userSessionToken',
    };

    try {
      GenericApiModel<ExplanationsResponseModel>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getExplanations,
        apiHeaders: headers,
        body: body,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          loggerService.logError("GetExplanations API Failed: $error");
          failure = failureType ?? ServerFailure(error);
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final Map<String, dynamic> responseData = response is String ? jsonDecode(response) : response;

            ExplanationsResponseModel explanationsResponse = ExplanationsResponseModel.fromJson(responseData);

            apiResponse = GenericApiModel<ExplanationsResponseModel>(
              messageStatus: messageStatus ?? 1,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: explanationsResponse,
            );
          } catch (e, stackTrace) {
            loggerService.logError("Error parsing GetExplanations response: $e");
            loggerService.logError("StackTrace: $stackTrace");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e, stackTrace) {
      loggerService.logError("Exception in getExplanations: $e");
      loggerService.logError("StackTrace: $stackTrace");
      return Left(UnknownFailure(e.toString()));
    }
  }
}
