package de.effigenix.application.masterdata.customer;

import de.effigenix.application.masterdata.customer.command.CreateCustomerCommand;
import de.effigenix.domain.masterdata.customer.Customer;
import de.effigenix.domain.masterdata.customer.CustomerDraft;
import de.effigenix.domain.masterdata.customer.CustomerError;
import de.effigenix.domain.masterdata.customer.CustomerRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class CreateCustomer {

    private final CustomerRepository customerRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<CustomerError, Customer> execute(CreateCustomerCommand cmd, ActorId performedBy) {
        var draft = new CustomerDraft(
                cmd.name(), cmd.type(), cmd.phone(), cmd.email(), cmd.contactPerson(),
                cmd.street(), cmd.houseNumber(), cmd.postalCode(), cmd.city(), cmd.country(),
                cmd.paymentDueDays(), cmd.paymentDescription()
        );

        Customer customer;
        switch (Customer.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> customer = val;
        }

        switch (customerRepository.existsByName(customer.name())) {
            case Result.Failure(var err) ->
                { return Result.failure(new CustomerError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new CustomerError.CustomerNameAlreadyExists(cmd.name()));
                }
            }
        }

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