package de.effigenix.application.masterdata.article;

import de.effigenix.domain.masterdata.article.Article;
import de.effigenix.domain.masterdata.article.ArticleError;
import de.effigenix.domain.masterdata.article.ArticleId;
import de.effigenix.domain.masterdata.article.ArticleRepository;
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 DeactivateArticle {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

    public DeactivateArticle(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.deactivate();

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