package de.effigenix.application.production;

import de.effigenix.domain.production.ProductionOrder;
import de.effigenix.domain.production.ProductionOrderError;
import de.effigenix.domain.production.ProductionOrderId;
import de.effigenix.domain.production.ProductionOrderRepository;
import de.effigenix.shared.common.Result;

public class GetProductionOrder {

    private final ProductionOrderRepository productionOrderRepository;

    public GetProductionOrder(ProductionOrderRepository productionOrderRepository) {
        this.productionOrderRepository = productionOrderRepository;
    }

    public Result<ProductionOrderError, ProductionOrder> execute(String id) {
        if (id == null || id.isBlank()) {
            return Result.failure(new ProductionOrderError.ProductionOrderNotFound(ProductionOrderId.of(id)));
        }

        return switch (productionOrderRepository.findById(ProductionOrderId.of(id))) {
            case Result.Failure(var err) -> Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
            case Result.Success(var opt) -> opt
                    .<Result<ProductionOrderError, ProductionOrder>>map(Result::success)
                    .orElseGet(() -> Result.failure(new ProductionOrderError.ProductionOrderNotFound(ProductionOrderId.of(id))));
        };
    }
}
