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

import '../../../domain/analytic/analytic.dart';

part 'sales_analytic_loader_event.dart';
part 'sales_analytic_loader_state.dart';
part 'sales_analytic_loader_bloc.freezed.dart';

@injectable
class SalesAnalyticLoaderBloc
    extends Bloc<SalesAnalyticLoaderEvent, SalesAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;
  SalesAnalyticLoaderBloc(this._analyticRepository)
    : super(SalesAnalyticLoaderState.initial()) {
    on<SalesAnalyticLoaderEvent>(_onSalesAnalyticLoaderEvent);
  }

  Future<void> _onSalesAnalyticLoaderEvent(
    SalesAnalyticLoaderEvent event,
    Emitter<SalesAnalyticLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOption: none()));

        final result = await _analyticRepository.getSales(
          dateFrom: e.startDate,
          dateTo: e.endDate,
        );

        await result.fold(
          (failure) async {
            emit(
              state.copyWith(
                isFetching: false,
                failureOption: optionOf(failure),
              ),
            );
          },
          (sales) async {
            emit(state.copyWith(isFetching: false, salesAnalytic: sales));
          },
        );
      },
    );
  }
}
