package com.braintree.graphql.commands.impl;

import com.braintree.command.result.BrainTreeVoidResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
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.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.commands.request.VoidRequest;
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.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 DefaultBrainTreeGraphQLVoidCommandTest {

    public static final String TRANSACTION_ID_PARAMETER = "transactionId";
    private static final String DEFINITION_FILE_NAME = "reverseTransaction";
    private static final String MUTATION_NAME = "reverseTransaction";
    private static final String REVERSAL_PARAMETER = "reversal";
    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 USD = "USD";
    private static final String RESULT_ERRORS = "errors";
    private static final String ERROR_MESSAGE = "Error message";
    private static final String LEGACY_ID = "legacyId";
    private static final String PAYPAL_ACCOUNT_INSTRUMENT_TYPE = "paypal_account";
    private static final String CAPTURE_ID = "captureId";
    private static final String LEGACY_CODE = "legacyCode";
    private static final String ERROR_MAP_KEY = "error";
    private static final String REQUEST_ID = "requestId";
    private static final String GRAPH_QL_ID_FROM_TRANSACTION = "GraphQLIdFromTransaction";
    private static final String REVERSAL_TRANSACTION_ID = "reversal_transaction_id";
    private static final String MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String REQUEST_TOKEN = "requestToken";
    private static final String VOID_TRANSACTION_LOG_TYPE = "[VOID TRANSACTION] ";
    private static final String PROCESSOR_RESPONSE_ERROR_MESSAGE = "processor response error message";
    private static final String PAYMENT_PROVIDER = "paymentProvider";

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

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLVoidCommand command;

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

    @Mock
    private Logger logger;

    private VoidRequest voidRequest;

    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private Map<String, Object> reverseTransactionMap;
    private BrainTreeTransaction brainTreeTransaction;
    private Calendar createdAt;
    private BrainTreePaymentMethodSnapshot paymentMethodSnapshot;

    @Before
    public void setUp() throws IOException {
        brainTreeTransaction = new BrainTreeTransaction();
        reverseTransactionMap = new HashMap<>();
        reverseTransactionMap.put(REVERSAL_PARAMETER, brainTreeTransaction);
        dataResult = new HashMap<>();
        dataResult.put(MUTATION_NAME, reverseTransactionMap);
        mapResult = new HashMap<>();
        mapResult.put(DATA_MAP_KEY, dataResult);

        createdAt = new GregorianCalendar();

        paymentMethodSnapshot = new BrainTreePaymentMethodSnapshot();
        paymentMethodSnapshot.setCaptureId(CAPTURE_ID);

        voidRequest = new VoidRequest(MERCHANT_TRANSACTION_CODE, REQUEST_ID, REQUEST_TOKEN, PAYMENT_PROVIDER);

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

    @Test
    public void shouldCreateVariablesMap() throws IOException {
        //given
        when(brainTreeTransactionService.getGraphQLIdFromTransaction(REQUEST_ID)).thenReturn(GRAPH_QL_ID_FROM_TRANSACTION);

        //when
        command.perform(voidRequest);

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

        Map<String, Object> input = (Map<String, Object>) variables.getValue().get(INPUT_PARAMETER);

        assertNotNull(input);
        assertEquals(GRAPH_QL_ID_FROM_TRANSACTION, input.get(TRANSACTION_ID_PARAMETER));
    }

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

        brainTreeTransaction.setStatus(BrainTreePaymentStatus.VOIDED);
        brainTreeTransaction.setAmount(monetaryAmount);
        brainTreeTransaction.setLegacyId(LEGACY_ID);
        brainTreeTransaction.setId(REVERSAL_TRANSACTION_ID);
        brainTreeTransaction.setCreatedAt(createdAt);
        brainTreeTransaction.setPaymentMethodSnapshot(paymentMethodSnapshot);

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

        //when
        BrainTreeVoidResult commandResult = command.perform(voidRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertEquals(MERCHANT_TRANSACTION_CODE, commandResult.getMerchantTransactionCode());
        assertEquals(REQUEST_ID, commandResult.getRequestId());
        assertEquals(REVERSAL_TRANSACTION_ID, commandResult.getTransactionGraphQLId());
        assertEquals(REQUEST_TOKEN, commandResult.getRequestToken());
        assertEquals(TransactionStatusDetails.SUCCESFULL, commandResult.getTransactionStatusDetails());
        assertEquals(TransactionStatus.ACCEPTED, commandResult.getTransactionStatus());
        assertEquals(AMOUNT, commandResult.getAmount().toString());
        assertEquals(USD, commandResult.getCurrencyIsoCode());
        assertNotNull(commandResult.getCreatedAt());
        assertEquals(PAYPAL_ACCOUNT_INSTRUMENT_TYPE, commandResult.getPaymentInstrumentType());
        assertNotNull(commandResult.getRequestBody());
        assertNotNull(commandResult.getResponseBody());

        verify(paymentInfoService).getPaymentInstrumentTypeBySnapshotAndOrigin(paymentMethodSnapshot);
        verify(loggingHandler).handleResult(VOID_TRANSACTION_LOG_TYPE, brainTreeTransaction);
    }

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

        brainTreeTransaction.setStatus(BrainTreePaymentStatus.VOIDED);
        brainTreeTransaction.setAmount(monetaryAmount);
        brainTreeTransaction.setPaymentMethodSnapshot(paymentMethodSnapshot);

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

        //when
        BrainTreeVoidResult commandResult = command.perform(voidRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertNull(commandResult.getCreatedAt());
    }

    @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);

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

        //when
        BrainTreeVoidResult commandResult = command.perform(voidRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertEquals(TransactionStatus.ERROR, 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());
        verify(paymentInfoService, never()).getPaymentInstrumentTypeBySnapshotAndOrigin(any(BrainTreePaymentMethodSnapshot.class));
    }

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

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

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

}
