package de.effigenix.application.masterdata.customer;

import de.effigenix.application.masterdata.customer.command.AddDeliveryAddressCommand;
import de.effigenix.domain.masterdata.customer.*;
import de.effigenix.shared.common.Address;
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 AddDeliveryAddress {

    private final CustomerRepository customerRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<CustomerError, Customer> execute(AddDeliveryAddressCommand 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();
            }
        }

        Address address;
        switch (Address.create(cmd.street(), cmd.houseNumber(), cmd.postalCode(), cmd.city(), cmd.country())) {
            case Failure(var msg) -> { return Result.failure(new CustomerError.ValidationFailure(msg)); }
            case Success(var val) -> address = val;
        }

        DeliveryAddress deliveryAddress;
        switch (DeliveryAddress.create(cmd.label(), address, cmd.contactPerson(), cmd.deliveryNotes())) {
            case Failure(var msg) -> { return Result.failure(new CustomerError.ValidationFailure(msg)); }
            case Success(var val) -> deliveryAddress = val;
        }
        customer.addDeliveryAddress(deliveryAddress);

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