package de.effigenix.infrastructure.inventory.event;

import de.effigenix.application.inventory.BookProductionConsumption;
import de.effigenix.application.inventory.command.BookProductionConsumptionCommand;
import de.effigenix.infrastructure.integration.event.ConsumptionRecordedIntegrationEvent;
import de.effigenix.shared.common.Result;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class ConsumptionRecordedInventoryListener {

    private static final System.Logger logger = System.getLogger(ConsumptionRecordedInventoryListener.class.getName());

    private final BookProductionConsumption bookProductionConsumption;

    public ConsumptionRecordedInventoryListener(BookProductionConsumption bookProductionConsumption) {
        this.bookProductionConsumption = bookProductionConsumption;
    }

    @EventListener
    public void on(ConsumptionRecordedIntegrationEvent event) {
        var cmd = new BookProductionConsumptionCommand(
                event.inputBatchReferenceId(),
                event.articleId(),
                event.quantityAmount(),
                event.quantityUnit()
        );
        switch (bookProductionConsumption.execute(cmd)) {
            case Result.Failure(var err) ->
                    logger.log(System.Logger.Level.WARNING,
                            "Failed to book production consumption for batch {0}: {1}",
                            event.inputBatchReferenceId(), err.message());
            case Result.Success(var ignored) ->
                    logger.log(System.Logger.Level.INFO,
                            "Booked production consumption for batch {0}, article {1}",
                            event.inputBatchReferenceId(), event.articleId());
        }
    }
}
