package de.effigenix.application.production;

import de.effigenix.application.production.command.CancelProductionOrderCommand;
import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

public class CancelProductionOrder {

    private final ProductionOrderRepository productionOrderRepository;
    private final AuthorizationPort authorizationPort;
    private final UnitOfWork unitOfWork;

    public CancelProductionOrder(
            ProductionOrderRepository productionOrderRepository,
            AuthorizationPort authorizationPort,
            UnitOfWork unitOfWork
    ) {
        this.productionOrderRepository = productionOrderRepository;
        this.authorizationPort = authorizationPort;
        this.unitOfWork = unitOfWork;
    }

    public Result<ProductionOrderError, ProductionOrder> execute(CancelProductionOrderCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)) {
            return Result.failure(new ProductionOrderError.Unauthorized("Not authorized to cancel production orders"));
        }

        var orderId = ProductionOrderId.of(cmd.productionOrderId());
        ProductionOrder order;
        switch (productionOrderRepository.findById(orderId)) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
            }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new ProductionOrderError.ProductionOrderNotFound(orderId));
                }
                order = opt.get();
            }
        }

        switch (order.cancel(cmd.reason())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        return unitOfWork.executeAtomically(() -> {
            switch (productionOrderRepository.save(order)) {
                case Result.Failure(var err) -> {
                    return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
                }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(order);
        });
    }
}
