package de.effigenix.application.masterdata;

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

    private final ArticleRepository articleRepository;

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

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

        switch (article.updateSalesUnitPrice(SalesUnitId.of(cmd.salesUnitId()), price)) {
            case Failure(var err) -> { return Result.failure(err); }
            case Success(var ignored) -> { }
        }

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

        return Result.success(article);
    }
}
