package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeCreatePaymentMethodRequest;
import com.braintree.command.result.BrainTreeCreatePaymentMethodResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.configuration.service.BrainTreeConfigService;
import com.braintree.customer.service.BrainTreeCustomerAccountService;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeVaultPaymentMethodInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
import com.braintree.hybris.data.graphql.commands.response.BrainTreePaymentMethodDetails;
import com.braintree.hybris.data.graphql.commands.response.BrainTreePaymentMethodOrigin;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeVaultPaymentMethodPayload;
import com.braintree.hybris.data.graphql.commands.response.BraintreePaymentMethodData;
import com.braintree.method.BrainTreePaymentService;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.payment.AdapterException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

    private static final String DEFINITION_FILE_NAME = "vaultPaymentMethod";
    private static final String MUTATION_NAME = "vaultPaymentMethod";
    private static final String INPUT_PARAMETER = "input";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String ERROR_MESSAGE = "Error message";
    private static final String ERROR_MAP_KEY = "error";
    private static final String RESULT_ERRORS = "errors";
    private static final String DATA_MAP_KEY = "data";
    private static final String CUSTOMER_ID = "customerId";
    private static final String GRAPH_QL_ID_FOR_CUSTOMER = "graphQlIdForCustomer";
    private static final String EMAIL = "email";
    private static final String LEGACY_ID = "legacyId";
    private static final String METHOD_NONCE = "methodNonce";
    private static final String DEVICE_DATA = "deviceData";
    private static final String PAYMENT_METHOD_ID = "paymentMethodId";
    private static final String CARD_HOLDER_FULL_NAME = "John Cena";
    private static final String EXPIRATION_MONTH = "1";
    private static final String EXPIRATION_YEAR = "2030";
    private static final String BRAND_CODE = "brandCode";
    private static final String LAST_4 = "4444";
    private static final String ORIGIN_TYPE = "origin_type";
    private static final String TYPENAME = "__typename";
    private static final String PAYMENT_PROVIDER_BY_DETAILS_AND_ORIGIN = "PaymentProviderByDetailsAndOrigin";
    private static final String IMAGE_SOURCE_BY_PAYMENT_PROVIDER_AND_CARD_TYPE = "ImageSourceByPaymentProviderAndCardType";
    private static final String MERCHANT_ACCOUNT = "merchantAccount";

    @Mock
    private ObjectMapper objectMapper;
    @Mock
    private BrainTreeCustomerAccountService brainTreeCustomerAccountService;
    @Mock
    private BrainTreePaymentService brainTreePaymentService;
    @Mock
    private BrainTreeConfigService brainTreeConfigService;
    @Mock
    private BraintreePaymentInfoService braintreePaymentInfoService;
    @Mock
    private DefaultBrainTreeLoggingHandler loggingHandler;

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLCreatePaymentMethodCommand command;

    @Captor
    private ArgumentCaptor<Map<String, Object>> variables;

    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private BrainTreeVaultPaymentMethodPayload vaultPaymentMethodPayload;
    private BrainTreeCreatePaymentMethodRequest createPaymentMethodRequest;
    private BraintreePaymentMethodData paymentMethod;
    private BrainTreePaymentMethodDetails paymentMethodDetails;

    @Before
    public void setUp() throws IOException {
        paymentMethodDetails = new BrainTreePaymentMethodDetails();

        paymentMethod = new BraintreePaymentMethodData();
        paymentMethod.setDetails(paymentMethodDetails);

        vaultPaymentMethodPayload = new BrainTreeVaultPaymentMethodPayload();
        vaultPaymentMethodPayload.setPaymentMethod(paymentMethod);

        createPaymentMethodRequest =
                new BrainTreeCreatePaymentMethodRequest(MERCHANT_TRANSACTION_CODE, METHOD_NONCE, CUSTOMER_ID);

        dataResult = new HashMap<>();
        dataResult.put(MUTATION_NAME, vaultPaymentMethodPayload);
        mapResult = new HashMap<>();
        mapResult.put(DATA_MAP_KEY, dataResult);

        doReturn(mapResult).when(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        when(objectMapper.convertValue(vaultPaymentMethodPayload, BrainTreeVaultPaymentMethodPayload.class))
                .thenReturn(vaultPaymentMethodPayload);
    }

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        createPaymentMethodRequest.setAdvancedFraudTools(true);
        createPaymentMethodRequest.setDeviceData(DEVICE_DATA);

        when(brainTreeCustomerAccountService.getGraphQLIdForCustomer(CUSTOMER_ID)).thenReturn(GRAPH_QL_ID_FOR_CUSTOMER);
        when(brainTreeConfigService.isVerifyCard()).thenReturn(false);

        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), variables.capture());
        assertNotNull(variables.getValue());

        BrainTreeVaultPaymentMethodInput input = (BrainTreeVaultPaymentMethodInput) variables.getValue().get(INPUT_PARAMETER);

        assertNotNull(input);
        assertEquals(GRAPH_QL_ID_FOR_CUSTOMER, input.getCustomerId());
        assertEquals(METHOD_NONCE, input.getPaymentMethodId());

        assertNotNull(input.getVerification());
        assertTrue(input.getVerification().isSkip());

        assertNotNull(input.getRiskData());
        assertEquals(DEVICE_DATA, input.getRiskData().getDeviceData());

        verify(brainTreeCustomerAccountService).getGraphQLIdForCustomer(CUSTOMER_ID);
        verify(brainTreeConfigService).isVerifyCard();
        verify(loggingHandler).handleCreatePaymentMethodRequest(createPaymentMethodRequest);
    }

    @Test
    public void shouldNotSetRiskDataIfAdvancedFraudToolsIsFalseWhenCreateVariablesMap() throws IOException {
        //given
        createPaymentMethodRequest.setAdvancedFraudTools(false);

        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), variables.capture());
        assertNotNull(variables.getValue());

        BrainTreeVaultPaymentMethodInput input = (BrainTreeVaultPaymentMethodInput) variables.getValue().get(INPUT_PARAMETER);

        assertNotNull(input);
        assertNull(input.getRiskData());
    }

    @Test
    public void shouldNotSetCustomerIdIfRequestCustomerIdIsNullWhenCreateVariablesMap() throws IOException {
        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), variables.capture());
        assertNotNull(variables.getValue());

        BrainTreeVaultPaymentMethodInput input = (BrainTreeVaultPaymentMethodInput) variables.getValue().get(INPUT_PARAMETER);

        assertNotNull(input);
        assertNull(input.getCustomerId());
    }

    @Test
    public void shouldTranslateResponseWhenSuccessfulTransaction() throws IOException {
        //given
        BrainTreePaymentMethodOrigin paymentMethodOrigin = new BrainTreePaymentMethodOrigin();
        paymentMethodOrigin.setType(ORIGIN_TYPE);

        paymentMethod.setLegacyId(LEGACY_ID);
        paymentMethod.setId(PAYMENT_METHOD_ID);

        paymentMethodDetails.setEmail(EMAIL);
        paymentMethodDetails.setExpirationMonth(EXPIRATION_MONTH);
        paymentMethodDetails.setExpirationYear(EXPIRATION_YEAR);
        paymentMethodDetails.setBrandCode(BRAND_CODE);
        paymentMethodDetails.setLast4(LAST_4);
        paymentMethodDetails.setCardholderName(CARD_HOLDER_FULL_NAME);
        paymentMethodDetails.setOrigin(paymentMethodOrigin);
        paymentMethodDetails.set__typename(TYPENAME);

        when(braintreePaymentInfoService.getPaymentProviderByDetailsAndOrigin(TYPENAME, ORIGIN_TYPE))
                .thenReturn(PAYMENT_PROVIDER_BY_DETAILS_AND_ORIGIN);
        when(braintreePaymentInfoService.getImageSourceByPaymentProviderAndCardType(PAYMENT_PROVIDER_BY_DETAILS_AND_ORIGIN, BRAND_CODE))
                .thenReturn(IMAGE_SOURCE_BY_PAYMENT_PROVIDER_AND_CARD_TYPE);

        //when
        BrainTreeCreatePaymentMethodResult commandResult = command.perform(createPaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertEquals(LEGACY_ID, commandResult.getPaymentMethodToken());
        assertEquals(PAYMENT_METHOD_ID, commandResult.getPaymentMethodGraphQLToken());
        assertEquals(EMAIL, commandResult.getEmail());
        assertEquals(EXPIRATION_MONTH, commandResult.getExpirationMonth());
        assertEquals(EXPIRATION_YEAR, commandResult.getExpirationYear());
        assertEquals(BRAND_CODE, commandResult.getCardType());
        assertEquals(LAST_4, commandResult.getLast4());
        assertEquals(CARD_HOLDER_FULL_NAME, commandResult.getCardholderName());
        assertNotNull(commandResult.getCardNumber());
        assertEquals(PAYMENT_PROVIDER_BY_DETAILS_AND_ORIGIN, commandResult.getPaymentProvider());
        assertEquals(IMAGE_SOURCE_BY_PAYMENT_PROVIDER_AND_CARD_TYPE, commandResult.getImageSource());

        verify(loggingHandler).handleResult(vaultPaymentMethodPayload);
        verify(braintreePaymentInfoService).getPaymentProviderByDetailsAndOrigin(TYPENAME, ORIGIN_TYPE);
        verify(braintreePaymentInfoService)
                .getImageSourceByPaymentProviderAndCardType(PAYMENT_PROVIDER_BY_DETAILS_AND_ORIGIN, BRAND_CODE);
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldNotSetCardNumberIfLast4IsNullWhenTranslateResponse() throws IOException {
        //when
        BrainTreeCreatePaymentMethodResult commandResult = command.perform(createPaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertNull(commandResult.getLast4());
        assertNull(commandResult.getCardholderName());

        verify(loggingHandler).handleResult(vaultPaymentMethodPayload);
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldNotSetPaymentMethodDetailsIfNullWhenTranslateResponse() throws IOException {
        //given
        paymentMethod.setLegacyId(LEGACY_ID);
        paymentMethod.setId(PAYMENT_METHOD_ID);

        //when
        BrainTreeCreatePaymentMethodResult commandResult = command.perform(createPaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertEquals(LEGACY_ID, commandResult.getPaymentMethodToken());
        assertEquals(PAYMENT_METHOD_ID, commandResult.getPaymentMethodGraphQLToken());
        assertNull(commandResult.getEmail());
        assertNull(commandResult.getExpirationMonth());
        assertNull(commandResult.getExpirationYear());
        assertNull(commandResult.getCardType());
        assertNull(commandResult.getLast4());
        assertNull(commandResult.getCardholderName());
        assertNull(commandResult.getCardNumber());
        assertNull(commandResult.getPaymentProvider());
        assertNull(commandResult.getImageSource());

        verify(braintreePaymentInfoService)
                .getImageSourceByPaymentProviderAndCardType(null, null);
        verify(loggingHandler).handleResult(vaultPaymentMethodPayload);
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldNotSetPaymentMethodDataIfNullWhenTranslateResponse() throws IOException {
        //given
        vaultPaymentMethodPayload.setPaymentMethod(null);
        //when
        BrainTreeCreatePaymentMethodResult commandResult = command.perform(createPaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertNull(commandResult.getPaymentMethodToken());
        assertNull(commandResult.getPaymentMethodGraphQLToken());
        assertNull(commandResult.getEmail());
        assertNull(commandResult.getExpirationMonth());
        assertNull(commandResult.getExpirationYear());
        assertNull(commandResult.getCardType());
        assertNull(commandResult.getLast4());
        assertNull(commandResult.getCardholderName());
        assertNull(commandResult.getCardNumber());
        assertNull(commandResult.getPaymentProvider());
        assertNull(commandResult.getImageSource());

        verify(braintreePaymentInfoService, never()).getPaymentProviderByDetailsAndOrigin(anyString(), anyString());
        verify(braintreePaymentInfoService, never())
                .getImageSourceByPaymentProviderAndCardType(anyString(), anyString());
        verify(loggingHandler).handleResult(vaultPaymentMethodPayload);
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test(expected = AdapterException.class)
    public void shouldThrowExceptionIfGraphQLResponseContainsErrorWhenProcess() throws IOException {
        //given
        BrainTreeErrorDefinition brainTreeError = new BrainTreeErrorDefinition();
        brainTreeError.setMessage(ERROR_MESSAGE);
        Map<String, Object> errorMap = Map.of(ERROR_MAP_KEY, brainTreeError);
        List<Map<String, Object>> errorList = new ArrayList<>();
        errorList.add(errorMap);

        mapResult.put(RESULT_ERRORS, errorList);

        when(objectMapper.convertValue(errorMap, BrainTreeErrorDefinition.class)).thenReturn(brainTreeError);

        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(objectMapper).convertValue(errorMap, BrainTreeErrorDefinition.class);
    }

    @Test(expected = AdapterException.class)
    public void shouldThrowErrorWhenGraphQLCallFails() throws IOException {
        //given
        doThrow(IOException.class).when(command).makeGraphQlCall(any(), any());

        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldAddVerificationInputToRequest() throws IOException {
        when(brainTreeConfigService.isVerifyCard()).thenReturn(true);
        when(brainTreeConfigService.getMerchantAccountIdForCurrentSiteAndCurrency()).thenReturn(MERCHANT_ACCOUNT);

        //when
        command.perform(createPaymentMethodRequest);

        //then
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), variables.capture());

        BrainTreeVaultPaymentMethodInput input = (BrainTreeVaultPaymentMethodInput) variables.getValue().get(INPUT_PARAMETER);
        assertEquals(MERCHANT_ACCOUNT, input.getVerification().getMerchantAccountId());
        assertFalse(input.getVerification().isSkip());
    }

}
