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

abstract class NotificationsRepo {
  Future<Either<Failure, GenericApiModel<List<NotificationResponseModel>>>> getAllNotifications({
    required int notificationStatusID,
    required int pagingSize,
    required int currentPage,
  });

  Future<Either<Failure, GenericApiModel<List<NotificationResponseModel>>>> markAsRead({
    required int notificationID,
  });
}

class NotificationsRepoImp implements NotificationsRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<List<NotificationResponseModel>>>> getAllNotifications({
    required int notificationStatusID,
    required int pagingSize,
    required int currentPage,
  }) async {
    Map<String, dynamic> mapDevice = {
      "NotificationStatusID": notificationStatusID,
      "pagingSize": pagingSize,
      "currentPage": currentPage,
    };

    try {
      GenericApiModel<List<NotificationResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_ALL_NOTIFICATIONS,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_GetAllNotificationsFromPool'];
            if (list == null || list.isEmpty) {
              // Return empty list if no notifications
              apiResponse = GenericApiModel<List<NotificationResponseModel>>(
                messageStatus: messageStatus,
                statusCode: statusCode,
                errorMessage: null,
                data: [],
              );
              return;
            }

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

            apiResponse = GenericApiModel<List<NotificationResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: notifications,
            );
          } 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<NotificationResponseModel>>>> markAsRead({required int notificationID}) async {
    Map<String, dynamic> mapDevice = {"NotificationPoolID": notificationID};

    try {
      GenericApiModel<List<NotificationResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        PUSH_NOTIFICATION_SET_MESSAGES_FROM_POOL_AS_READ,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<List<NotificationResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: [],
            );
          } 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()));
    }
  }
}
