package de.effigenix.application.inventory;

import de.effigenix.domain.inventory.Stock;
import de.effigenix.domain.inventory.StockError;
import de.effigenix.domain.inventory.StockId;
import de.effigenix.domain.inventory.StockRepository;
import de.effigenix.shared.common.Result;

public class GetStock {

    private final StockRepository stockRepository;

    public GetStock(StockRepository stockRepository) {
        this.stockRepository = stockRepository;
    }

    public Result<StockError, Stock> execute(String stockId) {
        if (stockId == null || stockId.isBlank()) {
            return Result.failure(new StockError.StockNotFound(stockId));
        }

        return switch (stockRepository.findById(StockId.of(stockId))) {
            case Result.Failure(var err) -> Result.failure(new StockError.RepositoryFailure(err.message()));
            case Result.Success(var opt) -> opt
                    .<Result<StockError, Stock>>map(Result::success)
                    .orElseGet(() -> Result.failure(new StockError.StockNotFound(stockId)));
        };
    }
}
