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';
import '../../../domain/analytic/repositories/i_analytic_repository.dart';
import '../../../domain/outlet/outlet.dart';

part 'inventory_report_event.dart';
part 'inventory_report_state.dart';
part 'inventory_report_bloc.freezed.dart';

@injectable
class InventoryReportBloc
    extends Bloc<InventoryReportEvent, InventoryReportState> {
  final IAnalyticRepository _analyticRepository;
  final IOutletRepository _outletRepository;
  InventoryReportBloc(this._analyticRepository, this._outletRepository)
    : super(InventoryReportState.initial()) {
    on<InventoryReportEvent>(_onInventoryReportEvent);
  }

  Future<void> _onInventoryReportEvent(
    InventoryReportEvent event,
    Emitter<InventoryReportState> emit,
  ) {
    return event.map(
      fetchedOutlet: (e) async {
        emit(
          state.copyWith(isFetchingOutlet: true, failureOptionOutlet: none()),
        );

        final result = await _outletRepository.currentOutlet();

        var data = result.fold(
          (f) => state.copyWith(failureOptionOutlet: optionOf(f)),
          (currentOutlet) => state.copyWith(outlet: currentOutlet),
        );

        emit(data.copyWith(isFetchingOutlet: false));
      },
      fetchedInventory: (e) async {
        emit(
          state.copyWith(
            isFetching: true,
            failureOptionInventoryAnalytic: none(),
          ),
        );

        final result = await _analyticRepository.getInventory(
          dateFrom: e.dateFrom,
          dateTo: e.dateTo,
        );

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

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