package de.effigenix.application.masterdata;

import de.effigenix.domain.masterdata.*;
import de.effigenix.shared.common.Result;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional(readOnly = true)
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)));
        };
    }
}
