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

abstract class TermsConditionsRepo {
  Future<Either<Failure, String>> getTermsConditions();
}

class TermsConditionsRepoImp implements TermsConditionsRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, String>> getTermsConditions() async {
    Failure? failure;
    String? html;

    try {
      await apiClient.post(
        ApiConsts.getTermsConditions,
        body: <String, dynamic>{},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType ?? ServerFailure(error.toString());
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {

            final content = response['UserAgreementContent'];

            if (content is String && content.isNotEmpty) {
              html = content;
            } else {
              failure = DataParsingFailure(
                  'UserAgreementContent is null or not String');
            }
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
    } catch (e) {
      failure = UnknownFailure(e.toString());
    }

    if (failure != null) return Left(failure!);
    if (html == null || html!.isEmpty) {
      return Left(ServerFailure('No terms and conditions returned'));
    }

    return Right(html!);
  }
}

