package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeUpdateCreditCardRequest;
import com.braintree.command.result.BrainTreeBillingAddressResult;
import com.braintree.command.result.BrainTreeUpdateCreditCardBillingAddressResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeAddressInput;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeUpdateCreditCardBillingAddressInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeAddress;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeUpdatePaymentMethodPayLoad;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import com.braintreegateway.ValidationError;
import com.braintreegateway.ValidationErrorCode;
import com.braintreegateway.exceptions.NotFoundException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.payment.AdapterException;
import de.hybris.platform.payment.dto.BillingInfo;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import org.apache.commons.lang.StringUtils;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
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 DefaultBrainTreeGraphQLUpdateCreditCardBillingAddressCommandTest {

    private static final String DEFINITION_FILE_NAME = "updateCreditCardBillingAddress";
    private static final String MUTATION_NAME = "updateCreditCardBillingAddress";
    private static final String DATA_MAP_KEY = "data";
    private static final String AMOUNT = "12.44";
    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 GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD = "GraphQLTokenForPaymentMethod";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String UPDATE_CREDIT_CARD_REQUEST_TOKEN = "updateCreditCardRequestToken";

    @Mock
    private Converter<BillingInfo, BrainTreeAddressInput> braintreeBillingInfoToGraphQLAddressInputConverter;
    @Mock
    private Converter<BrainTreeAddress, BrainTreeBillingAddressResult> graphQLAddressToAddressResult;
    @Mock
    private DefaultBrainTreeLoggingHandler loggingHandler;
    @Mock
    private ObjectMapper objectMapper;
    @Mock
    private BraintreePaymentInfoService paymentInfoService;

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLUpdateCreditCardBillingAddressCommand command;

    @Mock
    private Logger logger;

    @Mock
    private BrainTreeAddressInput addressInput;

    @Mock
    private BrainTreeAddress billingAddress;

    @Mock
    private BrainTreeBillingAddressResult billingAddressResult;

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

    private BrainTreeUpdateCreditCardRequest updateCreditCardRequest;
    private BrainTreeUpdatePaymentMethodPayLoad updatePaymentMethodPayLoad;
    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private BigDecimal bigDecimalAmount;
    private Calendar createdAt;

    @Before
    public void setUp() throws IOException {
        updatePaymentMethodPayLoad = new BrainTreeUpdatePaymentMethodPayLoad();
        updateCreditCardRequest = new BrainTreeUpdateCreditCardRequest(MERCHANT_TRANSACTION_CODE);
        updateCreditCardRequest.setToken(UPDATE_CREDIT_CARD_REQUEST_TOKEN);

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

        bigDecimalAmount = new BigDecimal(AMOUNT);
        createdAt = new GregorianCalendar();

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

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        BillingInfo billingAddress = new BillingInfo();
        updateCreditCardRequest.setBillingInfo(billingAddress);
        when(braintreeBillingInfoToGraphQLAddressInputConverter.convert(billingAddress)).thenReturn(addressInput);

        //when
        command.perform(updateCreditCardRequest);

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

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

        assertNotNull(input);
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, input.getPaymentMethodId());
        assertNotNull(input.getBillingAddress());
        assertEquals(addressInput, input.getBillingAddress());

        verify(braintreeBillingInfoToGraphQLAddressInputConverter).convert(billingAddress);
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

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

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

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

        assertNotNull(input);
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, input.getPaymentMethodId());
        assertNull(input.getBillingAddress());

        verify(braintreeBillingInfoToGraphQLAddressInputConverter, never()).convert(any(BillingInfo.class));
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
    }

    @Test
    public void shouldTranslateResponseWhenSuccessfulTransaction() throws IOException {
        //given
        updatePaymentMethodPayLoad.setBillingAddress(billingAddress);
        when(graphQLAddressToAddressResult.convert(billingAddress)).thenReturn(billingAddressResult);

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

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, commandResult.getPaymentMethodToken());
        assertEquals(billingAddressResult, commandResult.getBillingAddressResult());
        assertEquals(TransactionStatus.ACCEPTED, commandResult.getTransactionStatus());
        assertEquals(TransactionStatusDetails.SUCCESFULL, commandResult.getTransactionStatusDetails());

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

    @Test
    public void shouldTranslateResponseWhenTransactionPayloadIsNull() throws IOException {
        //given
        when(objectMapper.convertValue(updatePaymentMethodPayLoad, BrainTreeUpdatePaymentMethodPayLoad.class))
                .thenReturn(null);

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

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getPaymentMethodToken());
        assertNull(commandResult.getBillingAddressResult());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());

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

    @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 shouldTranslateResponseWhenUnsuccessfulTransaction() throws IOException {
        //given
        ValidationError validationError =
                new ValidationError(StringUtils.EMPTY, ValidationErrorCode.UNKNOWN_VALIDATION_ERROR, ERROR_MESSAGE);
        Map<String, Object> errorMap = Map.of(ERROR_MAP_KEY, validationError);
        List<Map<String, Object>> errorList = new ArrayList<>();
        errorList.add(errorMap);

        mapResult.put(RESULT_ERRORS, errorList);

        when(objectMapper.convertValue(errorMap, ValidationError.class)).thenReturn(validationError);

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

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertEquals(ValidationErrorCode.UNKNOWN_VALIDATION_ERROR.toString(), commandResult.getErrorCode());
        assertEquals(ERROR_MESSAGE, commandResult.getErrorMessage());

        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(loggingHandler).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();
    }

}
