package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeCustomerRequest;
import com.braintree.command.result.BrainTreeCustomerResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.customer.service.BrainTreeCustomerAccountService;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeDeleteCustomerInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorExtension;
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.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 DefaultBrainTreeGraphQLRemoveCustomerCommandTest {

    private static final String DEFINITION_FILE_NAME = "deleteCustomer";
    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 LEGACY_CODE = "legacyCode";
    private static final String ERROR_MAP_KEY = "error";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String CUSTOMER_ID = "customerId";
    private static final String GRAPH_QL_ID_FOR_CUSTOMER = "graphQLIdForCustomer";

    @Mock
    private BrainTreeCustomerAccountService brainTreeCustomerAccountService;

    @Mock
    private ObjectMapper objectMapper;

    @Mock
    private DefaultBrainTreeLoggingHandler loggingHandler;

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLRemoveCustomerCommand command;

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

    @Mock
    private Logger logger;

    private Map<String, Object> mapResult;
    private BrainTreeCustomerRequest brainTreeCustomerRequest;

    @Before
    public void setUp() throws IOException {
        brainTreeCustomerRequest = new BrainTreeCustomerRequest(MERCHANT_TRANSACTION_CODE);

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

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

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        brainTreeCustomerRequest.setCustomerId(CUSTOMER_ID);

        when(brainTreeCustomerAccountService.getGraphQLIdForCustomer(CUSTOMER_ID)).thenReturn(GRAPH_QL_ID_FOR_CUSTOMER);

        //when
        command.perform(brainTreeCustomerRequest);

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

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

        assertNotNull(input);
        assertEquals(GRAPH_QL_ID_FOR_CUSTOMER, input.getCustomerId());
        verify(brainTreeCustomerAccountService).getGraphQLIdForCustomer(CUSTOMER_ID);
    }

    @Test
    public void shouldCreateVariablesMapWhenCustomerIdIsEmpty() throws IOException {
        //when
        command.perform(brainTreeCustomerRequest);

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

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

        assertNotNull(input);
        assertNull(input.getCustomerId());
        verify(brainTreeCustomerAccountService, never()).getGraphQLIdForCustomer(anyString());
    }

    @Test
    public void shouldSuccessfullyPerform() throws IOException {
        //when
        BrainTreeCustomerResult commandResult = command.perform(brainTreeCustomerRequest);

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

    @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
        BrainTreeCustomerResult commandResult = command.perform(brainTreeCustomerRequest);

        //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 shouldTranslateNotFoundResponse() throws IOException {
        //given
        doThrow(NotFoundException.class).when(command).makeGraphQlCall(any(), any());

        //when
        BrainTreeCustomerResult commandResult = command.perform(brainTreeCustomerRequest);

        //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(brainTreeCustomerRequest);

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

}
