package de.effigenix.infrastructure.inventory.event;

import de.effigenix.application.inventory.BookProductionOutput;
import de.effigenix.application.inventory.command.BookProductionOutputCommand;
import de.effigenix.infrastructure.integration.event.BatchCompletedIntegrationEvent;
import de.effigenix.shared.common.Result;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class BatchCompletedInventoryListener {

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

    private final BookProductionOutput bookProductionOutput;

    public BatchCompletedInventoryListener(BookProductionOutput bookProductionOutput) {
        this.bookProductionOutput = bookProductionOutput;
    }

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