package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.AddStockBatchCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;

public class AddStockBatch {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

    public AddStockBatch(StockRepository stockRepository, UnitOfWork unitOfWork) {
        this.stockRepository = stockRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<StockError, StockBatch> execute(AddStockBatchCommand cmd) {
        // 1. Stock laden
        Stock stock;
        switch (stockRepository.findById(StockId.of(cmd.stockId()))) {
            case Result.Failure(var err) ->
                { return Result.failure(new StockError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new StockError.StockNotFound(cmd.stockId()));
                }
                stock = opt.get();
            }
        }

        // 2. Batch hinzufügen (Domain validiert)
        var draft = new StockBatchDraft(
                cmd.batchId(), cmd.batchType(),
                cmd.quantityAmount(), cmd.quantityUnit(),
                cmd.expiryDate()
        );

        StockBatch batch;
        switch (stock.addBatch(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> batch = val;
        }

        // 3. Stock speichern
        return unitOfWork.executeAtomically(() -> {
            switch (stockRepository.save(stock)) {
                case Result.Failure(var err) ->
                    { return Result.failure(new StockError.RepositoryFailure(err.message())); }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(batch);
        });
    }
}
