package de.effigenix.application.masterdata.article;

import de.effigenix.application.masterdata.article.command.AddSalesUnitCommand;
import de.effigenix.domain.masterdata.article.*;
import de.effigenix.shared.common.Money;
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 AddSalesUnit {

    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<ArticleError, Article> execute(AddSalesUnitCommand 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();
            }
        }

        Money price;
        switch (Money.tryEuro(cmd.price())) {
            case Failure(var msg) -> { return Result.failure(new ArticleError.ValidationFailure(msg)); }
            case Success(var val) -> price = val;
        }

        SalesUnit salesUnit;
        switch (SalesUnit.create(cmd.unit(), cmd.priceModel(), price)) {
            case Failure(var err) -> { return Result.failure(err); }
            case Success(var val) -> salesUnit = val;
        }

        switch (article.addSalesUnit(salesUnit)) {
            case Failure(var err) -> { return Result.failure(err); }
            case Success(var ignored) -> { }
        }

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