import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:enaklo_pos/data/models/request/payment_request.dart';
import 'package:enaklo_pos/data/models/response/payment_response_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'payment_form_event.dart';
part 'payment_form_state.dart';
part 'payment_form_bloc.freezed.dart';

class PaymentFormBloc extends Bloc<PaymentFormEvent, PaymentFormState> {
  final OrderRemoteDatasource _orderRemoteDatasource;
  PaymentFormBloc(this._orderRemoteDatasource)
      : super(PaymentFormState.initial()) {
    on<_Create>(
      (event, emit) async {
        emit(const _Loading());

        try {
          final result =
              await _orderRemoteDatasource.createPayment(event.payment);

          result.fold(
            (error) => emit(_Error(error)),
            (success) => emit(_Success(success.data!)),
          );
        } catch (e) {
          emit(_Error("Failed to create payment: $e"));
        }
      },
    );
    on<_CreateSplitBill>(
      (event, emit) async {
        emit(const _Loading());

        try {
          final result = await _orderRemoteDatasource
              .createPaymentSplitBill(event.payment);

          result.fold(
            (error) => emit(_Error(error)),
            (success) => emit(_Success(success.data!)),
          );
        } catch (e) {
          emit(_Error("Failed to create payment split bill: $e"));
        }
      },
    );
  }
}
