package de.effigenix.application.masterdata.customer;

import de.effigenix.domain.masterdata.customer.Customer;
import de.effigenix.domain.masterdata.customer.CustomerError;
import de.effigenix.domain.masterdata.customer.CustomerId;
import de.effigenix.domain.masterdata.customer.CustomerRepository;
import de.effigenix.shared.common.Result;

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

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