package de.effigenix.application.masterdata;

import de.effigenix.application.masterdata.command.RemoveSalesUnitCommand;
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 RemoveSalesUnit {

    private final ArticleRepository articleRepository;

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

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

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

        switch (article.removeSalesUnit(SalesUnitId.of(cmd.salesUnitId()))) {
            case Failure(var err) -> { return Result.failure(err); }
            case Success(var ignored) -> { }
        }

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

        return Result.success(article);
    }
}
