package de.effigenix.application.production;

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

    private final RecipeRepository recipeRepository;
    private final AuthorizationPort authorizationPort;
    private final RecipeCycleChecker cycleChecker;
    private final UnitOfWork unitOfWork;

    public AddRecipeIngredient(RecipeRepository recipeRepository, AuthorizationPort authorizationPort,
                               RecipeCycleChecker cycleChecker, UnitOfWork unitOfWork) {
        this.recipeRepository = recipeRepository;
        this.authorizationPort = authorizationPort;
        this.cycleChecker = cycleChecker;
        this.unitOfWork = unitOfWork;
    }

    public Result<RecipeError, Recipe> execute(AddRecipeIngredientCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.RECIPE_WRITE)) {
            return Result.failure(new RecipeError.Unauthorized("Not authorized to modify recipes"));
        }

        var recipeId = RecipeId.of(cmd.recipeId());

        Recipe recipe;
        switch (recipeRepository.findById(recipeId)) {
            case Result.Failure(var err) ->
                { return Result.failure(new RecipeError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new RecipeError.RecipeNotFound(recipeId));
                }
                recipe = opt.get();
            }
        }

        if (cmd.subRecipeId() != null) {
            switch (cycleChecker.check(cmd.recipeId(), cmd.subRecipeId())) {
                case Result.Failure(var err) -> { return Result.failure(err); }
                case Result.Success(var ignored) -> { }
            }
        }

        var draft = new IngredientDraft(
                cmd.position(), cmd.articleId(), cmd.quantity(),
                cmd.uom(), cmd.subRecipeId(), cmd.substitutable()
        );

        switch (recipe.addIngredient(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

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