package com.braintree.interceptors;

import com.braintree.command.request.BrainTreeCustomerRequest;
import com.braintree.command.request.BrainTreeDeletePaymentMethodRequest;
import com.braintree.command.result.BrainTreeFindCustomerResult;
import com.braintree.command.result.BrainTreePaymentDetailsResult;
import com.braintree.method.impl.DefaultBrainTreePaymentService;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.RemoveInterceptor;

import static java.util.Optional.ofNullable;
import static org.apache.commons.lang.StringUtils.isNotBlank;

public class BrainTreeCustomerRemoveInterceptor implements RemoveInterceptor<CustomerModel> {

    private DefaultBrainTreePaymentService brainTreePaymentService;

    @Override
    public void onRemove(CustomerModel customerModel, InterceptorContext interceptorContext) {
        String brainTreeCustomerId = customerModel.getBraintreeCustomerId();
        if (isNotBlank(brainTreeCustomerId)) {
            final BrainTreeCustomerRequest customerRequest = new BrainTreeCustomerRequest(brainTreeCustomerId);
            customerRequest.setCustomerId(brainTreeCustomerId);

            final BrainTreeFindCustomerResult findCustomerResult = brainTreePaymentService.findCustomer(customerRequest);
            ofNullable(findCustomerResult.getPaymentMethods())
                    .ifPresent(x -> x.stream()
                            .map(BrainTreePaymentDetailsResult::getPaymentMethodToken)
                            .forEach(token -> brainTreePaymentService.deletePaymentMethod(new BrainTreeDeletePaymentMethodRequest(brainTreeCustomerId, token))));

            brainTreePaymentService.removeCustomer(customerRequest);
        }
    }

    public void setBrainTreePaymentService(DefaultBrainTreePaymentService brainTreePaymentService) {
        this.brainTreePaymentService = brainTreePaymentService;
    }

}
