package de.effigenix.application.masterdata;

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

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

@Transactional
public class DeactivateArticle {

    private final ArticleRepository articleRepository;

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

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

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

        return Result.success(article);
    }
}
