import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'refund_event.dart';
part 'refund_state.dart';
part 'refund_bloc.freezed.dart';

class RefundBloc extends Bloc<RefundEvent, RefundState> {
  final OrderRemoteDatasource _orderRemoteDatasource;

  RefundBloc(this._orderRemoteDatasource) : super(const RefundState.initial()) {
    on<RefundEvent>((event, emit) async {
      await event.when(
        refundPayment: (paymentId, reason, refundAmount) =>
            _onRefundPayment(paymentId, reason, refundAmount, emit),
      );
    });
  }

  Future<void> _onRefundPayment(
    String orderId,
    String reason,
    int refundAmount,
    Emitter<RefundState> emit,
  ) async {
    emit(const RefundState.loading());

    final result = await _orderRemoteDatasource.refundPayment(
      orderId: orderId,
      reason: reason,
      refundAmount: refundAmount,
    );

    result.fold(
      (error) => emit(RefundState.error(error)),
      (success) => emit(const RefundState.success()),
    );
  }
}
