package de.effigenix.application.masterdata;

import de.effigenix.domain.masterdata.*;
import de.effigenix.shared.common.Result;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional(readOnly = true)
public class GetCustomer {

    private final CustomerRepository customerRepository;

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

    public Result<CustomerError, Customer> execute(CustomerId customerId) {
        return switch (customerRepository.findById(customerId)) {
            case Failure(var err) ->
                Result.failure(new CustomerError.RepositoryFailure(err.message()));
            case Success(var opt) ->
                opt.map(Result::<CustomerError, Customer>success)
                    .orElseGet(() -> Result.failure(new CustomerError.CustomerNotFound(customerId)));
        };
    }
}
