import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/api/api_client.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/emergency_services/model/resp_model/ProjectAvgERWaitingTime.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

import '../../core/api_consts.dart' show GET_NEAREST_HOSPITAL;

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


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

  EmergencyServicesRepoImpl({required this.loggerService, required this.apiClient});
  @override
  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()));
    }
  }
}
