import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:enaklo_pos/data/models/response/order_response_model.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'void_order_event.dart';
part 'void_order_state.dart';
part 'void_order_bloc.freezed.dart';

class VoidOrderBloc extends Bloc<VoidOrderEvent, VoidOrderState> {
  final OrderRemoteDatasource _orderRemoteDatasource;

  VoidOrderBloc(this._orderRemoteDatasource)
      : super(const VoidOrderState.initial()) {
    on<_VoidOrder>(_onVoidOrder);
  }

  Future<void> _onVoidOrder(
    _VoidOrder event,
    Emitter<VoidOrderState> emit,
  ) async {
    emit(const VoidOrderState.loading());

    final result = await _orderRemoteDatasource.voidOrder(
      orderId: event.orderId,
      reason: event.reason,
      type: event.type,
      orderItems: event.orderItems,
    );

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