package de.effigenix.application.masterdata.article;

import de.effigenix.application.masterdata.article.command.CreateArticleCommand;
import de.effigenix.domain.masterdata.article.Article;
import de.effigenix.domain.masterdata.article.ArticleDraft;
import de.effigenix.domain.masterdata.article.ArticleError;
import de.effigenix.domain.masterdata.article.ArticleRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class CreateArticle {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<ArticleError, Article> execute(CreateArticleCommand cmd, ActorId performedBy) {
        var draft = new ArticleDraft(
                cmd.name(), cmd.articleNumber(), cmd.categoryId(),
                cmd.unit(), cmd.priceModel(), cmd.price()
        );

        Article article;
        switch (Article.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> article = val;
        }

        switch (articleRepository.existsByArticleNumber(article.articleNumber())) {
            case Result.Failure(var err) ->
                { return Result.failure(new ArticleError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new ArticleError.ArticleNumberAlreadyExists(cmd.articleNumber()));
                }
            }
        }

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