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;

import java.util.List;

public class ListRecipes {

    private final RecipeRepository recipeRepository;
    private final AuthorizationPort authorizationPort;

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

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

        switch (recipeRepository.findAll()) {
            case Result.Failure(var err) ->
                { return Result.failure(new RecipeError.RepositoryFailure(err.message())); }
            case Result.Success(var recipes) ->
                { return Result.success(recipes); }
        }
    }

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

        switch (recipeRepository.findByStatus(status)) {
            case Result.Failure(var err) ->
                { return Result.failure(new RecipeError.RepositoryFailure(err.message())); }
            case Result.Success(var recipes) ->
                { return Result.success(recipes); }
        }
    }
}
