package de.effigenix.application.masterdata.article;

import de.effigenix.application.masterdata.article.command.UpdateArticleCommand;
import de.effigenix.domain.masterdata.article.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class UpdateArticle {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<ArticleError, Article> execute(UpdateArticleCommand cmd, ActorId performedBy) {
        var articleId = ArticleId.of(cmd.articleId());

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

        var draft = new ArticleUpdateDraft(cmd.name(), cmd.categoryId());
        switch (article.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

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