package de.effigenix.application.production;

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

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

    public CreateProductionOrder(
            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(CreateProductionOrderCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)) {
            return Result.failure(new ProductionOrderError.Unauthorized("Not authorized to create production orders"));
        }

        // Verify recipe exists and is ACTIVE
        Recipe recipe;
        switch (recipeRepository.findById(RecipeId.of(cmd.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.ValidationFailure(
                            "Recipe with ID '" + cmd.recipeId() + "' not found"));
                }
                recipe = opt.get();
            }
        }

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

        // Create production order
        var draft = new ProductionOrderDraft(
                cmd.recipeId(),
                cmd.plannedQuantity(),
                cmd.plannedQuantityUnit(),
                cmd.plannedDate(),
                cmd.priority(),
                cmd.notes()
        );

        ProductionOrder order;
        switch (ProductionOrder.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> order = val;
        }

        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);
        });
    }
}
