package de.effigenix.application.inventory;

import de.effigenix.domain.inventory.InventoryAction;
import de.effigenix.domain.inventory.Stock;
import de.effigenix.domain.inventory.StockError;
import de.effigenix.domain.inventory.StockRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

import java.util.List;

public class ListStocksBelowMinimum {

    private final StockRepository stockRepository;
    private final AuthorizationPort authPort;

    public ListStocksBelowMinimum(StockRepository stockRepository, AuthorizationPort authPort) {
        this.stockRepository = stockRepository;
        this.authPort = authPort;
    }

    public Result<StockError, List<Stock>> execute(ActorId performedBy) {
        if (!authPort.can(performedBy, InventoryAction.STOCK_READ)) {
            return Result.failure(new StockError.Unauthorized("Not authorized to list stocks below minimum"));
        }
        return switch (stockRepository.findAllBelowMinimumLevel()) {
            case Result.Failure(var err) -> Result.failure(new StockError.RepositoryFailure(err.message()));
            case Result.Success(var val) -> Result.success(val);
        };
    }
}
