package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeUpdateCreditCardRequest;
import com.braintree.command.result.BrainTreeUpdateCreditCardBillingAddressResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeVerifyCreditCardInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeVerification;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeVerifyPaymentMethodPayload;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import com.braintreegateway.exceptions.NotFoundException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.payment.AdapterException;
import org.apache.log4j.Logger;
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.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 DefaultBrainTreeGraphQLVerifyCreditCardCommandTest {

    private static final String VERIFIED = "VERIFIED";
    private static final String DEFINITION_FILE_NAME = "verifyCreditCard";
    private static final String DATA_MAP_KEY = "data";
    private static final String INPUT_PARAMETER = "input";
    private static final String RESULT_ERRORS = "errors";
    private static final String ERROR_MESSAGE = "Error message";
    private static final String ERROR_MAP_KEY = "error";
    private static final String PAYMENT_METHOD_TOKEN = "paymentMethodToken";
    private static final String GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD = "GraphQLTokenForPaymentMethod";
    private static final String CV_2_NUMBER = "413";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String REJECTED = "REJECTED";

    @Mock
    private DefaultBrainTreeLoggingHandler loggingHandler;
    @Mock
    private ObjectMapper objectMapper;
    @Mock
    private BraintreePaymentInfoService paymentInfoService;

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLVerifyCreditCardCommand command;

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

    @Mock
    private Logger logger;

    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private BrainTreeUpdateCreditCardRequest updateCreditCardRequest;
    private BrainTreeVerifyPaymentMethodPayload paymentMethodPayload;
    private BrainTreeVerification verification;

    @Before
    public void setUp() throws IOException {
        verification = new BrainTreeVerification();
        paymentMethodPayload = new BrainTreeVerifyPaymentMethodPayload();
        updateCreditCardRequest = new BrainTreeUpdateCreditCardRequest(MERCHANT_TRANSACTION_CODE);
        updateCreditCardRequest.setToken(PAYMENT_METHOD_TOKEN);

        dataResult = new HashMap<>();
        dataResult.put(DEFINITION_FILE_NAME, paymentMethodPayload);
        mapResult = new HashMap<>();
        mapResult.put(DATA_MAP_KEY, dataResult);

        when(paymentInfoService.getGraphQLTokenForPaymentMethod(PAYMENT_METHOD_TOKEN)).thenReturn(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD);
        doReturn(mapResult).when(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        when(objectMapper.convertValue(paymentMethodPayload, BrainTreeVerifyPaymentMethodPayload.class))
                .thenReturn(paymentMethodPayload);
        when(loggingHandler.getLogger()).thenReturn(logger);
    }

    @Test
    public void shouldCreateVariableMap() throws IOException {
        //given
        updateCreditCardRequest.setCvvNonce(CV_2_NUMBER);

        //when
        command.perform(updateCreditCardRequest);

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

        BrainTreeVerifyCreditCardInput input = (BrainTreeVerifyCreditCardInput) variables.getValue().get(INPUT_PARAMETER);
        assertNotNull(input);
        assertNotNull(input.getOptions());
        assertEquals(CV_2_NUMBER, input.getOptions().getTokenizedCvv());
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, input.getPaymentMethodId());
    }

    @Test
    public void shouldCreateVariableMapWhenRequestCvvNonceIsNull() throws IOException {
        //when
        command.perform(updateCreditCardRequest);

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

        BrainTreeVerifyCreditCardInput input = (BrainTreeVerifyCreditCardInput) variables.getValue().get(INPUT_PARAMETER);
        assertNotNull(input);
        assertNull(input.getOptions());
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, input.getPaymentMethodId());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateResponseWhenSuccessfulTransaction() throws IOException {
        //given
        verification.setStatus(VERIFIED);
        paymentMethodPayload.setVerification(verification);

        //when
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateResponseWhenPayloadVerificationHasDifferentStatus() throws IOException {
        //given
        verification.setStatus(REJECTED);
        paymentMethodPayload.setVerification(verification);

        //when
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateResponseWhenPayloadVerificationIsNull() throws IOException {
        //when
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateResponseWhenPayloadIsNull() throws IOException {
        //given
        when(objectMapper.convertValue(paymentMethodPayload, BrainTreeVerifyPaymentMethodPayload.class))
                .thenReturn(null);

        //when
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateErrorResponseWhenGraphQLResponseContainsError() 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
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertEquals(ERROR_MESSAGE, commandResult.getErrorMessage());

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

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

        //when
        command.perform(updateCreditCardRequest);

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

    @Test
    public void shouldTranslateNotFoundResponse() throws IOException {
        //given
        doThrow(NotFoundException.class).when(command).makeGraphQlCall(any(), any());

        //when
        BrainTreeUpdateCreditCardBillingAddressResult commandResult = command.perform(updateCreditCardRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNotNull(commandResult.getErrorMessage());

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

}
