import 'package:baseproject/core/common/index.dart';
import 'package:baseproject/features/repositories/hra_repository_models.dart';
import 'package:baseproject/features/usecases/order/order_use_cases.dart';

class OrderDetailViewModel {
  const OrderDetailViewModel({
    this.isLoading = false,
    this.order,
  });

  final bool isLoading;
  final OrderDto? order;

  OrderDetailViewModel copyWith({
    bool? isLoading,
    OrderDto? order,
  }) {
    return OrderDetailViewModel(
      isLoading: isLoading ?? this.isLoading,
      order: order ?? this.order,
    );
  }
}

class OrderDetailBloc extends BaseCubit<BaseStateBloc<OrderDetailViewModel>> {
  OrderDetailBloc(this._orderUseCases)
      : super(
          InitState<OrderDetailViewModel>(
            const OrderDetailViewModel(),
          ),
        );

  final OrderUseCases _orderUseCases;

  Future<void> loadDetail(int id) async {
    final currentModel = state.model;

    emit(
      LoadingState<OrderDetailViewModel>(
        currentModel.copyWith(isLoading: true),
      ),
    );

    final result = await _orderUseCases.getOrderDetail(id);

    result.fold(
      (error) {
        showErrorMessage(error);
        emit(
          LoadedState<OrderDetailViewModel>(
            currentModel.copyWith(isLoading: false),
          ),
        );
      },
      (order) {
        emit(
          LoadedState<OrderDetailViewModel>(
            currentModel.copyWith(
              isLoading: false,
              order: order,
            ),
          ),
        );
      },
    );
  }
}

