package de.effigenix.application.masterdata.customer;

import de.effigenix.application.masterdata.customer.command.SetFrameContractCommand;
import de.effigenix.domain.masterdata.article.ArticleId;
import de.effigenix.domain.masterdata.customer.*;
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 java.util.ArrayList;

import static de.effigenix.shared.common.Result.*;

public class SetFrameContract {

    private final CustomerRepository customerRepository;
    private final UnitOfWork unitOfWork;

    public SetFrameContract(CustomerRepository customerRepository, UnitOfWork unitOfWork) {
        this.customerRepository = customerRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<CustomerError, Customer> execute(SetFrameContractCommand cmd, ActorId performedBy) {
        var customerId = CustomerId.of(cmd.customerId());

        Customer customer;
        switch (customerRepository.findById(customerId)) {
            case Failure(var err) ->
                { return Result.failure(new CustomerError.RepositoryFailure(err.message())); }
            case Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new CustomerError.CustomerNotFound(customerId));
                }
                customer = opt.get();
            }
        }

        var lineItems = new ArrayList<ContractLineItem>();
        for (var li : cmd.lineItems()) {
            Money price;
            switch (Money.tryEuro(li.agreedPrice())) {
                case Failure(var msg) -> { return Result.failure(new CustomerError.ValidationFailure(msg)); }
                case Success(var val) -> price = val;
            }

            ContractLineItem item;
            switch (ContractLineItem.create(ArticleId.of(li.articleId()), price, li.agreedQuantity(), li.unit())) {
                case Failure(var msg) -> { return Result.failure(new CustomerError.ValidationFailure(msg)); }
                case Success(var val) -> item = val;
            }
            lineItems.add(item);
        }

        FrameContract contract;
        switch (FrameContract.create(cmd.validFrom(), cmd.validUntil(), cmd.rhythm(), lineItems)) {
            case Failure(var msg) -> { return Result.failure(new CustomerError.InvalidFrameContract(msg)); }
            case Success(var val) -> contract = val;
        }

        switch (customer.setFrameContract(contract)) {
            case Failure(var err) -> { return Result.failure(err); }
            case Success(var ignored) -> { }
        }

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