package de.effigenix.application.masterdata.supplier;

import de.effigenix.application.masterdata.supplier.command.RemoveSupplierCommand;
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.domain.masterdata.supplier.SupplierId;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

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

public class RemoveSupplier {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<ArticleError, Article> execute(RemoveSupplierCommand 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();
            }
        }
        article.removeSupplierReference(SupplierId.of(cmd.supplierId()));

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