import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../../domain/entities/order_entity.dart';
import '../../domain/usecases/get_open_orders_usecase.dart';
import '../../domain/usecases/get_order_history_usecase.dart';
import 'package:injectable/injectable.dart';

part 'order_tabs_event.dart';
part 'order_tabs_state.dart';

@injectable
class OrderTabsBloc extends Bloc<OrderTabsEvent, OrderTabsState> {
  OrderTabsBloc(this._openOrdersUseCase, this._historyUseCase)
      : super(const OrderTabsInitial()) {
    on<FetchOpenOrders>(_onFetchOpen);
    on<FetchOrderHistory>(_onFetchHistory);
  }

  final GetOpenOrdersUseCase _openOrdersUseCase;
  final GetOrderHistoryUseCase _historyUseCase;

  Future<void> _onFetchOpen(
      FetchOpenOrders event, Emitter<OrderTabsState> emit) async {
    emit(const OrderTabsLoading());
    final result = await _openOrdersUseCase(event.symbol);
    result.fold(
      (failure) => emit(OrderTabsError(message: failure.message)),
      (orders) => emit(OpenOrdersLoaded(orders: orders)),
    );
  }

  Future<void> _onFetchHistory(
      FetchOrderHistory event, Emitter<OrderTabsState> emit) async {
    emit(const OrderTabsLoading());
    final result = await _historyUseCase(event.symbol);
    result.fold(
      (failure) => emit(OrderTabsError(message: failure.message)),
      (orders) => emit(OrderHistoryLoaded(orders: orders)),
    );
  }
}
