import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/usecase/apply_promo_code_usecase.dart';
import '../event/promo_code_event.dart';
import '../state/promo_code_state.dart';

class PromoCodeBloc extends Bloc<PromoCodeEvent, PromoCodeState> {
  final ApplyPromoCodeUsecase _applyPromoCodeUsecase;

  PromoCodeBloc(this._applyPromoCodeUsecase) : super(const PromoCodeState()) {
    on<PromoCodeApplyRequested>(_onApplyRequested);
    on<PromoCodeReset>(_onReset);
  }

  Future<void> _onApplyRequested(
      PromoCodeApplyRequested event,
      Emitter<PromoCodeState> emit,
      ) async {
    emit(state.copyWith(status: PromoCodeStatus.loading));

    try {
      final result = await _applyPromoCodeUsecase(event.code);
      emit(state.copyWith(
        status: PromoCodeStatus.success,
        newBalance: result.balance,
      ));
    } catch (e) {
      emit(state.copyWith(
        status: PromoCodeStatus.failure,
        errorMessage: e.toString(),
      ));
    }
  }

  void _onReset(PromoCodeReset event, Emitter<PromoCodeState> emit) {
    emit(const PromoCodeState());
  }
}