package de.effigenix.application.production;

import de.effigenix.application.production.command.ReleaseProductionOrderCommand;
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 ReleaseProductionOrder {

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

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

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

        // Load production order
        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();
            }
        }

        // Verify recipe is still ACTIVE
        Recipe recipe;
        switch (recipeRepository.findById(order.recipeId())) {
            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.RecipeNotFound(order.recipeId()));
                }
                recipe = opt.get();
            }
        }

        if (recipe.status() != RecipeStatus.ACTIVE) {
            return Result.failure(new ProductionOrderError.RecipeNotActive(recipe.id()));
        }

        // Release
        switch (order.release()) {
            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);
        });
    }
}
