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 static de.effigenix.shared.common.Result.*;

public class GetArticle {

    private final ArticleRepository articleRepository;

    public GetArticle(ArticleRepository articleRepository) {
        this.articleRepository = articleRepository;
    }

    public Result<ArticleError, Article> execute(ArticleId articleId) {
        return switch (articleRepository.findById(articleId)) {
            case Failure(var err) ->
                Result.failure(new ArticleError.RepositoryFailure(err.message()));
            case Success(var opt) ->
                opt.map(Result::<ArticleError, Article>success)
                    .orElseGet(() -> Result.failure(new ArticleError.ArticleNotFound(articleId)));
        };
    }
}
