import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:enaklo_pos/presentation/home/models/product_quantity.dart';
import 'package:enaklo_pos/core/extensions/string_ext.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'add_order_items_event.dart';
part 'add_order_items_state.dart';
part 'add_order_items_bloc.freezed.dart';

class AddOrderItemsBloc extends Bloc<AddOrderItemsEvent, AddOrderItemsState> {
  final OrderRemoteDatasource orderRemoteDatasource;
  
  AddOrderItemsBloc(
    this.orderRemoteDatasource,
  ) : super(const _Initial()) {
    on<_AddOrderItems>((event, emit) async {
      emit(const _Loading());
      
      try {
        // Convert ProductQuantity list to the format expected by the API
        final orderItems = event.items.map((item) => {
          'id_product': item.product.productId,
          'quantity': item.quantity,
          'price': item.product.price!.toIntegerFromText,
          'notes': item.notes,
        }).toList();

        log("Adding order items: ${orderItems.toString()}");
        
        final result = await orderRemoteDatasource.addOrderItems(
          event.orderId,
          orderItems,
        );

        result.fold(
          (error) => emit(_Error(error)),
          (success) => emit(const _Success()),
        );
      } catch (e) {
        log("Error in AddOrderItemsBloc: $e");
        emit(_Error("Failed to add order items: $e"));
      }
    });
  }
} 