import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/customer/customer.dart';

part 'customer_point_loader_event.dart';
part 'customer_point_loader_state.dart';
part 'customer_point_loader_bloc.freezed.dart';

@injectable
class CustomerPointLoaderBloc
    extends Bloc<CustomerPointLoaderEvent, CustomerPointLoaderState> {
  final ICustomerRepository _repository;
  CustomerPointLoaderBloc(this._repository)
    : super(CustomerPointLoaderState.initial()) {
    on<CustomerPointLoaderEvent>(_onCustomerPointLoaderEvent);
  }

  Future<void> _onCustomerPointLoaderEvent(
    CustomerPointLoaderEvent event,
    Emitter<CustomerPointLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(
          state.copyWith(isFetching: true, failureOptionCustomerPoint: none()),
        );

        final result = await _repository.getPoints();

        var data = result.fold(
          (f) => state.copyWith(failureOptionCustomerPoint: optionOf(f)),
          (customerPoint) => state.copyWith(customerPoint: customerPoint),
        );

        emit(data.copyWith(isFetching: false));
      },
    );
  }
}
