package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeDeletePaymentMethodRequest;
import com.braintree.command.result.BrainTreePaymentMethodResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeDeletePaymentMethodFromVaultInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorExtension;
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.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.verify;
import static org.mockito.Mockito.when;

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

    private static final String DEFINITION_FILE_NAME = "deletePaymentMethod";
    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 TOKEN = "token";
    private static final String GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD = "GraphQLTokenForPaymentMethod";
    private static final String LEGACY_CODE = "legacyCode";

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

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLDeletePaymentMethodCommand command;

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

    @Mock
    private Logger logger;

    private Map<String, Object> mapResult;
    private BrainTreeDeletePaymentMethodRequest deletePaymentMethodRequest;

    @Before
    public void setUp() throws IOException {
        deletePaymentMethodRequest = new BrainTreeDeletePaymentMethodRequest(MERCHANT_TRANSACTION_CODE, TOKEN);
        mapResult = new HashMap<>();

        doReturn(mapResult).when(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        when(loggingHandler.getLogger()).thenReturn(logger);
    }

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        when(paymentInfoService.getGraphQLTokenForPaymentMethod(TOKEN)).thenReturn(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD);

        //when
        command.perform(deletePaymentMethodRequest);

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

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

        assertNotNull(input);
        assertEquals(GRAPH_QL_TOKEN_FOR_PAYMENT_METHOD, input.getPaymentMethodId());
        verify(paymentInfoService).getGraphQLTokenForPaymentMethod(TOKEN);
    }

    @Test
    public void shouldTranslateErrorResponseWhenGraphQLResponseContainsError() throws IOException {
        //given
        BrainTreeErrorExtension errorExtension = new BrainTreeErrorExtension();
        errorExtension.setLegacyCode(LEGACY_CODE);
        BrainTreeErrorDefinition brainTreeError = new BrainTreeErrorDefinition();
        brainTreeError.setMessage(ERROR_MESSAGE);
        brainTreeError.setExtensions(errorExtension);
        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
        BrainTreePaymentMethodResult commandResult = command.perform(deletePaymentMethodRequest);

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

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

    @Test
    public void shouldTranslateErrorResponseWhenLegacyCodeIsNull() throws IOException {
        //given
        BrainTreeErrorExtension errorExtension = new BrainTreeErrorExtension();
        BrainTreeErrorDefinition brainTreeError = new BrainTreeErrorDefinition();
        brainTreeError.setMessage(ERROR_MESSAGE);
        brainTreeError.setExtensions(errorExtension);
        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
        BrainTreePaymentMethodResult commandResult = command.perform(deletePaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(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
        BrainTreePaymentMethodResult commandResult = command.perform(deletePaymentMethodRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNotNull(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(deletePaymentMethodRequest);

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

}
