import 'package:dartz/dartz.dart';
import '../../core/api/api_client.dart';
import '../../core/api_consts.dart';
import '../../core/common_models/generic_api_model.dart';
import '../../core/exceptions/api_failure.dart';
import '../../services/logger_service.dart';

abstract class MonthlyReportsRepo {
  Future<Either<Failure, GenericApiModel<dynamic>>> saveMonthlyReport({
    String? email,
  });
}

class MonthlyReportsRepoImp implements MonthlyReportsRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<dynamic>>> saveMonthlyReport({
    String? email,
  }) async {
    try {
      Failure? failure;

      GenericApiModel<dynamic>? reportApiResponse;

      await apiClient.post(
        ApiConsts.getMonthlyReports,
        body: <String, dynamic>{},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            reportApiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: response,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (reportApiResponse == null) return Left(ServerFailure("Unknown error"));

      if ((reportApiResponse!.messageStatus ?? 0) != 1) {
        return Right(reportApiResponse!);
      }

      GenericApiModel<dynamic>? emailApiResponse;

      final Map<String, dynamic> emailRequest = <String, dynamic>{};

      if (email != null && email.trim().isNotEmpty) {
        emailRequest["Email"] = email.trim();
      }

      await apiClient.post(
        ApiConsts.updatePatientEmail,
        body: emailRequest,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            emailApiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: response,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (emailApiResponse == null) return Left(ServerFailure("Unknown error"));

      return Right(emailApiResponse!);
    } catch (e) {
      loggerService.logError("MonthlyReportsRepo.saveMonthlyReport error: $e");
      return Left(UnknownFailure(e.toString()));
    }
  }
}
