package de.effigenix.application.masterdata.customer;

import de.effigenix.application.masterdata.customer.command.UpdateCustomerCommand;
import de.effigenix.domain.masterdata.customer.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class UpdateCustomer {

    private final CustomerRepository customerRepository;
    private final UnitOfWork unitOfWork;

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

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

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

        var draft = new CustomerUpdateDraft(
                cmd.name(), cmd.phone(), cmd.email(), cmd.contactPerson(),
                cmd.street(), cmd.houseNumber(), cmd.postalCode(), cmd.city(), cmd.country(),
                cmd.paymentDueDays(), cmd.paymentDescription()
        );
        switch (customer.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

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