import '../../core/failures.dart';
import '../../core/result.dart';
import '../../domain/entities/certificate.dart';
import '../../domain/repositories/certificate_repository.dart';
import '../../domain/service/security_service.dart';
import '../network/api_service.dart';
import '../exceptions/auth_exception.dart';
import '../exceptions/auth_block_exception.dart';
import '../exceptions/unauthorized_exception.dart';

class CertificateRepositoryImpl implements CertificateRepository {
  final ApiService apiService;
  final SecurityService securityService;

  CertificateRepositoryImpl(this.apiService, this.securityService);

  @override
  Future<Result<List<Certificate>>> getCertificates() async {
    try {
      final certificates = await apiService.getCertificates();
      return Success(certificates);
    } on AuthException catch (e) {
      return Failure(AuthFailure(e.attemptsLeft));
    } on AuthBlockException catch (_) {
      return Failure(AuthBlockFailure("Ошибка. Вы заблокированы."));
    } on UnauthorizedException catch (_) {
      return Failure(UnknownFailure("Неизвестная ошибка"));
    } catch (e) {
      return Failure(UnknownFailure("Неизвестная ошибка"));
    }
  }

  @override
  Future<Result<Map<String, dynamic>>> purchaseCertificate({
    required int certificateId,
    required int cardId,
  }) async {
    try {
      final result = await apiService.purchaseCertificate(
        certificateId: certificateId,
        cardId: cardId,
      );

      if (result != null) {
        return Success(result);
      } else {
        return Failure(UnknownFailure("Неизвестная ошибка"));
      }
    } on AuthException catch (e) {
      return Failure(AuthFailure(e.attemptsLeft));
    } on AuthBlockException catch (_) {
      return Failure(AuthBlockFailure("Ошибка. Вы заблокированы."));
    } on UnauthorizedException catch (_) {
      return Failure(UnknownFailure("Неизвестная ошибка"));
    } catch (e) {
      return Failure(UnknownFailure("Неизвестная ошибка"));
    }
  }
}
