package de.effigenix.application.masterdata;

import de.effigenix.domain.masterdata.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

import static de.effigenix.shared.common.Result.*;

public class ActivateArticle {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

    public ActivateArticle(ArticleRepository articleRepository, UnitOfWork unitOfWork) {
        this.articleRepository = articleRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<ArticleError, Article> execute(ArticleId articleId, ActorId performedBy) {
        Article article;
        switch (articleRepository.findById(articleId)) {
            case Failure(var err) ->
                { return Result.failure(new ArticleError.RepositoryFailure(err.message())); }
            case Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new ArticleError.ArticleNotFound(articleId));
                }
                article = opt.get();
            }
        }
        article.activate();

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