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/services_price_list/models/resp_models/services_price_list_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class ServicesPriceListRepo {
  Future<Either<Failure, GenericApiModel<List<ServicesPriceListResponseModel>>>> getServicesPriceList({
    String searchKey = "",
    int pageIndex = 0,
    int pageSize = 0,
  });
}

class ServicesPriceListRepoImp implements ServicesPriceListRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<List<ServicesPriceListResponseModel>>>> getServicesPriceList({
    String searchKey = "",
    int pageIndex = 0,
    int pageSize = 0,
  }) async {
    Map<String, dynamic> mapDevice = {
      "ID": 1,
      "SearchKey": searchKey,
      "PageIndex": pageIndex,
      "PageSize": pageSize,
      "RowCount": 0,
      "TokenID": "@dm!n"
    };

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

      await apiClient.post(
        GET_SERVICES_PRICE_LIST,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['getServicesPriceList'];
            if (list == null || list.isEmpty) {
              throw Exception("Services price list is empty");
            }

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

            apiResponse = GenericApiModel<List<ServicesPriceListResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: servicesList,
            );
          } 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()));
    }
  }
}

