// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import 'package:flutter_pos_ecommerce/module/ecommerce/data/datasources/discount_remote_datasource.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/data/models/responses/discount_response_model.dart';

part 'discount_bloc.freezed.dart';
part 'discount_event.dart';
part 'discount_state.dart';

class DiscountBloc extends Bloc<DiscountEvent, DiscountState> {
  final DiscountRemoteDatasource discountRemoteDatasource;
  DiscountBloc(
    this.discountRemoteDatasource,
  ) : super(const _Initial()) {
    on<_GetDiscounts>((event, emit) async {
      emit(const _Loading());
      final result = await discountRemoteDatasource.getDiscounts();
      result.fold(
        (l) => emit(_Error(l)),
        (r) => emit(_Loaded(r.data!)),
      );
    });
    on<_UpdateDiscount>((event, emit) async {
      emit(const _Loading());
      final result = await discountRemoteDatasource.updateDiscount(
        event.id,
        event.name,
        event.description,
        event.value,
      );
      result.fold(
        (l) => emit(_Error(l)),
        (r) {
          emit(const _Success('Discount updated successfully'));
          add(const DiscountEvent.getDiscounts());
        },
      );
    });
  }
}
