package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeAdjustAuthorizationRequest;
import com.braintree.command.result.BrainTreeAdjustedAuthorizationResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeUpdateTransactionAmountInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorDefinition;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeErrorExtension;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeMonetaryAmount;
import com.braintree.hybris.data.graphql.commands.response.BrainTreePaymentMethodSnapshot;
import com.braintree.hybris.data.graphql.commands.response.BrainTreePaymentStatus;
import com.braintree.hybris.data.graphql.commands.response.BrainTreePaymentStatusEvent;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeTransaction;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeTransactionAuthorizationProcessorResponse;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeTransactionPayload;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import com.braintree.transaction.service.BrainTreeTransactionService;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.payment.AdapterException;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
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 DefaultBraintreeGraphQLAdjustAuthorizationCommandTest {

    private static final String DEFINITION_FILE_NAME = "updateTransactionAmount";
    private static final String TRANSACTION_ID = "transactionId";
    private static final String AMOUNT = "12.44";
    private static final String INPUT_PARAMETER = "input";
    private static final String DATA_MAP_KEY = "data";
    private static final String USD_CURRENCY = "USD";
    private static final String GRAPH_QL_TRANSACTION_ID = "graphQlTransactionId";
    private static final String LEGACY_ID = "legacyId";
    private static final String AUTHORIZED = "AUTHORIZED";
    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 PROCESSOR_RESPONSE_ERROR_MESSAGE = "processor response error message";
    private static final String PAYMENT_INSTRUMENT_TYPE = "credit_card";

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

    @Spy
    @InjectMocks
    private DefaultBraintreeGraphQLAdjustAuthorizationCommand command;

    @Mock
    private Logger logger;

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

    private BrainTreeAdjustAuthorizationRequest adjustAuthorizationRequest;
    private BigDecimal bigDecimalAmount;
    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private BrainTreeTransactionPayload transactionPayload;
    private BrainTreeTransaction transaction;
    private Calendar createdAt;
    private BrainTreePaymentMethodSnapshot paymentMethodSnapshot;

    @Before
    public void setUp() throws IOException {
        paymentMethodSnapshot = new BrainTreePaymentMethodSnapshot();
        transaction = new BrainTreeTransaction();
        transactionPayload = new BrainTreeTransactionPayload();
        transactionPayload.setTransaction(transaction);

        bigDecimalAmount = new BigDecimal(AMOUNT);
        adjustAuthorizationRequest = new BrainTreeAdjustAuthorizationRequest(TRANSACTION_ID, bigDecimalAmount);
        createdAt = new GregorianCalendar();

        dataResult = Map.of(DEFINITION_FILE_NAME, transactionPayload);
        mapResult = new HashMap<>();
        mapResult.put(DATA_MAP_KEY, dataResult);

        doReturn(mapResult).when(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        when(objectMapper.convertValue(transactionPayload, BrainTreeTransactionPayload.class))
                .thenReturn(transactionPayload);
        when(loggingHandler.getLogger()).thenReturn(logger);
    }

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        when(objectMapper.convertValue(any(), eq(BrainTreeTransactionPayload.class))).thenReturn(null);
        when(brainTreeTransactionService.getGraphQLIdFromTransaction(TRANSACTION_ID)).thenReturn(GRAPH_QL_TRANSACTION_ID);

        //when
        command.perform(adjustAuthorizationRequest);

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

        BrainTreeUpdateTransactionAmountInput inputResult = (BrainTreeUpdateTransactionAmountInput) variables.getValue().get(INPUT_PARAMETER);
        assertNotNull(inputResult);
        assertEquals(inputResult.getTransactionId(), GRAPH_QL_TRANSACTION_ID);
        assertEquals(bigDecimalAmount, inputResult.getAmount());
    }

    @Test
    public void shouldTranslateResponseWhenSuccessfulResult() {
        //given
        BrainTreeMonetaryAmount monetaryAmount = new BrainTreeMonetaryAmount();
        monetaryAmount.setValue(AMOUNT);
        monetaryAmount.setCurrencyCode(USD_CURRENCY);

        transaction.setStatus(BrainTreePaymentStatus.AUTHORIZED);
        transaction.setAmount(monetaryAmount);
        transaction.setId(GRAPH_QL_TRANSACTION_ID);
        transaction.setLegacyId(LEGACY_ID);
        transaction.setCreatedAt(createdAt);
        transaction.setPaymentMethodSnapshot(paymentMethodSnapshot);

        when(paymentInfoService.getPaymentInstrumentTypeBySnapshotAndOrigin(paymentMethodSnapshot))
                .thenReturn(PAYMENT_INSTRUMENT_TYPE);

        //when
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertEquals(AUTHORIZED, commandResult.getStatus());

        assertNotNull(commandResult.getAmount());
        assertEquals(bigDecimalAmount, commandResult.getAmount());

        assertEquals(GRAPH_QL_TRANSACTION_ID, commandResult.getTransactionGraphQLId());
        assertEquals(LEGACY_ID, commandResult.getTransactionId());
        assertEquals(TransactionStatus.ACCEPTED, commandResult.getTransactionStatus());
        assertEquals(TransactionStatusDetails.SUCCESFULL, commandResult.getTransactionStatusDetails());
        assertNotNull(commandResult.getCreatedAt());
        assertEquals(PAYMENT_INSTRUMENT_TYPE, commandResult.getPaymentInstrumentType());
    }

    @Test
    public void shouldTranslateResponseWhenFailedTransaction() throws IOException {
        //given
        BrainTreeTransactionAuthorizationProcessorResponse processorResponse = new BrainTreeTransactionAuthorizationProcessorResponse();
        processorResponse.setMessage(PROCESSOR_RESPONSE_ERROR_MESSAGE);
        processorResponse.setLegacyCode(LEGACY_CODE);

        BrainTreePaymentStatusEvent statusEvent = new BrainTreePaymentStatusEvent();
        statusEvent.setProcessorResponse(processorResponse);

        transaction.setStatus(BrainTreePaymentStatus.FAILED);
        transaction.setStatusHistory(List.of(statusEvent));

        //when
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertEquals(TransactionStatus.REJECTED, commandResult.getTransactionStatus());
        assertEquals(PROCESSOR_RESPONSE_ERROR_MESSAGE, commandResult.getErrorMessage());
        assertEquals(LEGACY_CODE, commandResult.getErrorCode());
        assertNotNull(commandResult.getRequestBody());
        assertNotNull(commandResult.getResponseBody());

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

    @Test
    public void shouldTranslateResponseWhenTransactionStatusIsNull() {
        //when
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());

        assertNull(commandResult.getAmount());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getCreatedAt());
    }

    @Test
    public void shouldTranslateResponseWhenPayloadTransactionIsNull() {
        //given
        transactionPayload.setTransaction(null);

        //when
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());

        assertNull(commandResult.getAmount());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getCreatedAt());
    }

    @Test
    public void shouldTranslateResponseWhenPayloadIsNull() {
        //given
        when(objectMapper.convertValue(transactionPayload, BrainTreeTransactionPayload.class))
                .thenReturn(null);

        //when
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());

        assertNull(commandResult.getAmount());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getCreatedAt());
    }

    @Test
    public void shouldTranslateResponseWhenGraphQLResponseContainsError() 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
        BrainTreeAdjustedAuthorizationResult commandResult = command.perform(adjustAuthorizationRequest);

        //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(expected = AdapterException.class)
    public void shouldThrowErrorWhenGraphQLCallFails() throws IOException {
        //given
        doThrow(IOException.class).when(command).makeGraphQlCall(any(), any());

        //when
        command.perform(adjustAuthorizationRequest);

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

}
