package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeGenerateClientTokenRequest;
import com.braintree.command.result.BrainTreeGenerateClientTokenResult;
import com.braintree.configuration.service.BrainTreeConfigService;
import com.braintree.customer.service.BrainTreeCustomerAccountService;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeCreateClientTokenInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeCreateClientTokenPayload;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
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.assertNotNull;
import static org.junit.Assert.assertNull;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

    private static final String DEFINITION_FILE_NAME = "createClientToken";
    private static final String MUTATION_NAME = "createClientToken";
    private static final String DATA_MAP_KEY = "data";
    private static final String INPUT_PARAMETER = "input";
    private static final String MERCHANT_ACCOUNT_ID = "merchantAccountId";
    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 CUSTOMER_ID = "customerId";
    private static final String GRAPH_QL_ID_FOR_CUSTOMER = "graphQlIdForCustomer";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String CLIENT_TOKEN = "clientToken";

    @Mock
    private BrainTreeCustomerAccountService brainTreeCustomerAccountService;
    @Mock
    private ObjectMapper objectMapper;

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLGenerateClientTokenCommand command;

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

    private BrainTreeGenerateClientTokenRequest generateClientTokenRequest;
    private BrainTreeCreateClientTokenPayload createClientTokenPayload;
    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;

    @Before
    public void setUp() throws IOException {
        createClientTokenPayload = new BrainTreeCreateClientTokenPayload();
        generateClientTokenRequest = new BrainTreeGenerateClientTokenRequest(MERCHANT_TRANSACTION_CODE, CUSTOMER_ID);

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

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

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        generateClientTokenRequest.setMerchantAccount(MERCHANT_ACCOUNT_ID);
        when(brainTreeCustomerAccountService.getGraphQLIdForCustomer(CUSTOMER_ID)).thenReturn(GRAPH_QL_ID_FOR_CUSTOMER);

        //when
        command.perform(generateClientTokenRequest);

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

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

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

    @Test
    public void shouldCreateVariablesMapWhenCustomerIdAndMerchantAccountIsNull() throws IOException {
        //given
        generateClientTokenRequest.setCustomerId(null);

        //when
        command.perform(generateClientTokenRequest);

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

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

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

    @Test
    public void shouldTranslateResponseWhenSuccessfulTransaction() throws IOException {
        //given
        createClientTokenPayload.setClientToken(CLIENT_TOKEN);

        //when
        BrainTreeGenerateClientTokenResult commandResult = command.perform(generateClientTokenRequest);

        //then
        assertNotNull(commandResult);
        assertEquals(CLIENT_TOKEN, commandResult.getClientToken());
        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(objectMapper).convertValue(createClientTokenPayload, BrainTreeCreateClientTokenPayload.class);
    }

    @Test(expected = AdapterException.class)
    public void shouldThrowExceptionIfGraphQLResponseContainsError() 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(generateClientTokenRequest);

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

}
