import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/use_cases/claim_daily_usecase.dart';
import '../../domain/use_cases/get_wallet_usecase.dart';
import 'daily_status.dart';
import 'wallet_event.dart';
import 'wallet_state.dart';
import 'wallet_status.dart';

class WalletBloc extends Bloc<WalletEvent, WalletBlocState> {
  final GetWalletUseCase getWalletUseCase;
  final ClaimDailyUseCase claimDailyUseCase;

  WalletBloc(this.getWalletUseCase, this.claimDailyUseCase)
      : super(WalletBlocState.initial()) {
    on<LoadWalletEvent>((event, emit) async {
      emit(state.copyWith(walletStatus: WalletLoading()));
      final res = await getWalletUseCase(const NoParams());
      if (res is DataSuccess) {
        emit(state.copyWith(walletStatus: WalletLoaded(res.data!)));
      } else {
        emit(state.copyWith(walletStatus: WalletError(res.error!)));
      }
    });

    on<ClaimDailyEvent>((event, emit) async {
      emit(state.copyWith(dailyStatus: DailyLoading()));
      final res = await claimDailyUseCase(const NoParams());
      if (res is DataSuccess) {
        emit(state.copyWith(dailyStatus: DailySuccess(res.data!)));
        // پس از دریافت، کیف‌پول به‌روزرسانی شود.
        final w = await getWalletUseCase(const NoParams());
        if (w is DataSuccess) {
          emit(state.copyWith(walletStatus: WalletLoaded(w.data!)));
        }
      } else {
        emit(state.copyWith(dailyStatus: DailyError(res.error!)));
      }
    });
  }
}
