package de.effigenix.application.inventory;

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

public class UpdateStock {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<StockError, Stock> execute(UpdateStockCommand cmd) {
        // 1. Laden
        StockId stockId;
        try {
            stockId = StockId.of(cmd.stockId());
        } catch (IllegalArgumentException e) {
            return Result.failure(new StockError.StockNotFound(cmd.stockId()));
        }

        Stock stock;
        switch (stockRepository.findById(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. Draft bauen + Aggregate validieren lassen
        var draft = new StockUpdateDraft(
                cmd.minimumLevelAmount(), cmd.minimumLevelUnit(),
                cmd.minimumShelfLifeDays()
        );
        switch (stock.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. 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(stock);
        });
    }
}
