package de.effigenix.application.masterdata;

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

    private final ArticleRepository articleRepository;

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

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

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

        return Result.success(article);
    }
}
