package de.effigenix.application.masterdata;

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

@Transactional
public class CreateArticle {

    private final ArticleRepository articleRepository;

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

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

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