package de.effigenix.application.production;

import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

public class GetRecipe {

    private final RecipeRepository recipeRepository;
    private final AuthorizationPort authorizationPort;

    public GetRecipe(RecipeRepository recipeRepository, AuthorizationPort authorizationPort) {
        this.recipeRepository = recipeRepository;
        this.authorizationPort = authorizationPort;
    }

    public Result<RecipeError, Recipe> execute(RecipeId recipeId, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.RECIPE_READ)) {
            return Result.failure(new RecipeError.Unauthorized("Not authorized to read recipes"));
        }

        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));
                }
                return Result.success(opt.get());
            }
        }
    }
}
