package com.braintree.interceptors;

import com.braintree.command.result.BrainTreeFindCustomerResult;
import com.braintree.command.result.BrainTreePaymentDetailsResult;
import com.braintree.method.impl.DefaultBrainTreePaymentService;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class BrainTreeCustomerRemoveInterceptorTest {

    private static final String BRAIN_TREE_CUSTOMER_ID = "testCustomerId";
    private static final String PAYMENT_METHOD_TOKEN = "testToken";

    @Mock
    private CustomerModel customerModel;
    @Mock
    private InterceptorContext interceptorContext;
    @Mock
    private BrainTreeFindCustomerResult findCustomerResult;
    @Mock
    private BrainTreePaymentDetailsResult paymentDetailsResult;
    private List<BrainTreePaymentDetailsResult> paymentDetailsList;

    @Mock
    private DefaultBrainTreePaymentService brainTreePaymentService;

    @InjectMocks
    private BrainTreeCustomerRemoveInterceptor unit;

    @Test
    public void testDeleteCustomer() {
        paymentDetailsList = List.of(paymentDetailsResult);

        when(customerModel.getBraintreeCustomerId()).thenReturn(BRAIN_TREE_CUSTOMER_ID);
        when(brainTreePaymentService.findCustomer(any())).thenReturn(findCustomerResult);
        when(findCustomerResult.getPaymentMethods()).thenReturn(paymentDetailsList);
        when(paymentDetailsResult.getPaymentMethodToken()).thenReturn(PAYMENT_METHOD_TOKEN);

        unit.onRemove(customerModel, interceptorContext);

        verify(brainTreePaymentService).deletePaymentMethod(any());
    }

    @Test
    public void testShouldNotDeletePaymentMethodsIfTheyAreNull() {
        paymentDetailsList = List.of(paymentDetailsResult);

        when(customerModel.getBraintreeCustomerId()).thenReturn(BRAIN_TREE_CUSTOMER_ID);
        when(brainTreePaymentService.findCustomer(any())).thenReturn(findCustomerResult);

        unit.onRemove(customerModel, interceptorContext);

        verify(brainTreePaymentService, never()).deletePaymentMethod(any());
    }

    @Test
    public void testShouldNotDeletePaymentMethodsIfCustomerIdIsEmpty() {
        when(customerModel.getBraintreeCustomerId()).thenReturn(StringUtils.EMPTY);

        unit.onRemove(customerModel, interceptorContext);

        verify(brainTreePaymentService, never()).deletePaymentMethod(any());
    }

}
