package de.effigenix.application.production;

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

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

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

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

        var draft = new RecipeDraft(
                cmd.name(), cmd.version(), cmd.type(), cmd.description(),
                cmd.yieldPercentage(), cmd.shelfLifeDays(),
                cmd.outputQuantity(), cmd.outputUom(), cmd.articleId()
        );

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

        // Uniqueness check: Name + Version
        switch (recipeRepository.existsByNameAndVersion(cmd.name(), cmd.version())) {
            case Result.Failure(var err) ->
                { return Result.failure(new RecipeError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new RecipeError.NameAndVersionAlreadyExists(cmd.name(), cmd.version()));
                }
            }
        }

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