package de.effigenix.application.masterdata;

import de.effigenix.application.masterdata.command.RemoveDeliveryAddressCommand;
import de.effigenix.domain.masterdata.*;
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 RemoveDeliveryAddress {

    private final CustomerRepository customerRepository;

    public RemoveDeliveryAddress(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    public Result<CustomerError, Customer> execute(RemoveDeliveryAddressCommand 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();
            }
        }
        customer.removeDeliveryAddress(cmd.label());

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

        return Result.success(customer);
    }
}
