import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart';
import 'package:enaklo_pos/data/models/request/product_request_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'update_product_event.dart';
part 'update_product_state.dart';
part 'update_product_bloc.freezed.dart';

class UpdateProductBloc extends Bloc<UpdateProductEvent, UpdateProductState> {
  final ProductRemoteDatasource datasource;
  UpdateProductBloc(
    this.datasource,
  ) : super(const _Initial()) {
    on<_UpdateProduct>((event, emit) async {
      emit(const _Loading());

      try {
        final response = await datasource.updateProduct(event.product);
        response.fold(
          (l) => emit(_Error(l)),
          (r) async {
            emit(_Success('Product berhasil diupdate'));
          },
        );
      } catch (e) {
        log("Error in UpdateProductBloc: $e");
        emit(_Error('An error occurred: $e'));
      }
    });
  }
}
