package com.braintree.graphql.commands.impl;

import com.braintree.command.request.BrainTreeSubmitForSettlementTransactionRequest;
import com.braintree.command.result.BrainTreeSubmitForSettlementTransactionResult;
import com.braintree.commands.impl.DefaultBrainTreeLoggingHandler;
import com.braintree.configuration.service.BrainTreeConfigService;
import com.braintree.enums.BrainTreePaymentMethod;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeCaptureTransactionInput;
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.BrainTreeTransaction;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeTransactionPayload;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import com.braintree.service.BrainTreeDescriptorService;
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.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 DefaultBrainTreeGraphQLSubmitForSettlementTransactionCommandTest {

    private static final String DEFINITION_FILE_NAME = "captureTransaction";
    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 MERCHANT_TRANSACTION_CODE = "merchantTransactionCode";
    private static final String TRANSACTION_ID = "transactionId";
    private static final String ORDER_ID = "orderId";
    private static final String GRAPH_QL_ID_FROM_TRANSACTION = "graphQLIdFromTransaction";
    private static final String SETTLEMENT_TRANSACTION_ID = "settlementTransactionId";

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

    @Spy
    @InjectMocks
    private DefaultBrainTreeGraphQLSubmitForSettlementTransactionCommand command;

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

    @Mock
    private Logger logger;

    private Map<String, Object> mapResult;
    private Map<String, Object> dataResult;
    private BigDecimal bigDecimalAmount;
    @Mock
    BrainTreeConfigService configService;
    private Calendar createdAt;
    private BrainTreePaymentMethodSnapshot paymentMethodSnapshot;
    private BrainTreeTransactionPayload transactionPayload;
    private BrainTreeSubmitForSettlementTransactionRequest submitForSettlementTransactionRequest;
    private BrainTreeTransaction settlementTransaction;

    @Before
    public void setUp() throws IOException {
        settlementTransaction = new BrainTreeTransaction();
        transactionPayload = new BrainTreeTransactionPayload();
        transactionPayload.setTransaction(settlementTransaction);
        submitForSettlementTransactionRequest = new BrainTreeSubmitForSettlementTransactionRequest(MERCHANT_TRANSACTION_CODE);

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

        bigDecimalAmount = new BigDecimal(AMOUNT);
        createdAt = new GregorianCalendar();

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

        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
        submitForSettlementTransactionRequest.setTransactionId(TRANSACTION_ID);
        submitForSettlementTransactionRequest.setOrderId(ORDER_ID);
        submitForSettlementTransactionRequest.setAmount(bigDecimalAmount);
        when(brainTreeTransactionService.getGraphQLIdFromTransaction(TRANSACTION_ID)).thenReturn(GRAPH_QL_ID_FROM_TRANSACTION);

        //when
        command.perform(submitForSettlementTransactionRequest);

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

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

        assertEquals(GRAPH_QL_ID_FROM_TRANSACTION, input.getTransactionId());
        assertNotNull(input.getTransaction());
        assertEquals(ORDER_ID, input.getTransaction().getOrderId());
        assertEquals(AMOUNT, input.getTransaction().getAmount().toString());
    }

    @Test
    public void shouldCreateVariablesMapWhenOrderIdAndAmountAreMissed() throws IOException {
        //given
        submitForSettlementTransactionRequest.setTransactionId(TRANSACTION_ID);
        when(brainTreeTransactionService.getGraphQLIdFromTransaction(TRANSACTION_ID)).thenReturn(GRAPH_QL_ID_FROM_TRANSACTION);

        //when
        command.perform(submitForSettlementTransactionRequest);

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

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

        assertEquals(GRAPH_QL_ID_FROM_TRANSACTION, input.getTransactionId());
        assertNotNull(input.getTransaction());
        assertNull(input.getTransaction().getOrderId());
        assertNull(input.getTransaction().getAmount());
    }

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

        settlementTransaction.setStatus(BrainTreePaymentStatus.SETTLED);
        settlementTransaction.setLegacyId(LEGACY_ID);
        settlementTransaction.setId(SETTLEMENT_TRANSACTION_ID);
        settlementTransaction.setAmount(monetaryAmount);
        settlementTransaction.setCreatedAt(createdAt);

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

        //when
        BrainTreeSubmitForSettlementTransactionResult commandResult = command.perform(submitForSettlementTransactionRequest);

        //then
        assertNotNull(commandResult);
        assertTrue(commandResult.isSuccess());
        assertEquals(BrainTreePaymentStatus.SETTLED.name(), commandResult.getStatus());
        assertEquals(LEGACY_ID, commandResult.getTransactionId());
        assertEquals(SETTLEMENT_TRANSACTION_ID, commandResult.getTransactionGraphQLId());
        assertEquals(AMOUNT, commandResult.getAmount().toString());
        assertEquals(TransactionStatus.ACCEPTED, commandResult.getTransactionStatus());
        assertEquals(TransactionStatusDetails.SUCCESFULL, commandResult.getTransactionStatusDetails());
        assertEquals(CAPTURE_ID, commandResult.getCaptureId());
        assertEquals(PAYPAL_ACCOUNT_INSTRUMENT_TYPE, commandResult.getPaymentInstrumentType());
        assertNotNull(commandResult.getCreatedAt());

        verify(loggingHandler).handleResult(anyString(), eq(settlementTransaction));
        verify(paymentInfoService).getPaymentInstrumentTypeBySnapshotAndOrigin(paymentMethodSnapshot);
    }

    @Test
    public void shouldTranslateResponseWhenUnsuccessfulTransaction() 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
        BrainTreeSubmitForSettlementTransactionResult commandResult = command.perform(submitForSettlementTransactionRequest);

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

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

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

        //when
        BrainTreeSubmitForSettlementTransactionResult commandResult = command.perform(submitForSettlementTransactionRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());
        assertNull(commandResult.getMerchantTransactionCode());
        assertNull(commandResult.getRequestId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getRequestToken());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getCurrencyIsoCode());
        assertNull(commandResult.getCreatedAt());
        assertNull(commandResult.getCaptureId());
        assertNotNull(commandResult.getRequestBody());
        assertNotNull(commandResult.getResponseBody());

        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(paymentInfoService, never()).getPaymentInstrumentTypeBySnapshotAndOrigin(any(BrainTreePaymentMethodSnapshot.class));
    }

    @Test
    public void shouldTranslateResponseWhenSaleTransactionIsNull() throws IOException {
        //given
        transactionPayload.setTransaction(null);

        //when
        BrainTreeSubmitForSettlementTransactionResult commandResult = command.perform(submitForSettlementTransactionRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());
        assertNull(commandResult.getMerchantTransactionCode());
        assertNull(commandResult.getRequestId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getRequestToken());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getCurrencyIsoCode());
        assertNull(commandResult.getCreatedAt());
        assertNull(commandResult.getCaptureId());
        assertNotNull(commandResult.getRequestBody());
        assertNotNull(commandResult.getResponseBody());

        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(paymentInfoService, never()).getPaymentInstrumentTypeBySnapshotAndOrigin(any(BrainTreePaymentMethodSnapshot.class));
    }

    @Test
    public void shouldTranslateResponseWhenTransactionStatusIsNull() throws IOException {
        //when
        BrainTreeSubmitForSettlementTransactionResult commandResult = command.perform(submitForSettlementTransactionRequest);

        //then
        assertNotNull(commandResult);
        assertFalse(commandResult.isSuccess());
        assertNull(commandResult.getStatus());
        assertNull(commandResult.getMerchantTransactionCode());
        assertNull(commandResult.getRequestId());
        assertNull(commandResult.getTransactionId());
        assertNull(commandResult.getTransactionGraphQLId());
        assertNull(commandResult.getRequestToken());
        assertNull(commandResult.getTransactionStatus());
        assertNull(commandResult.getTransactionStatusDetails());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getAmount());
        assertNull(commandResult.getCurrencyIsoCode());
        assertNull(commandResult.getCreatedAt());
        assertNull(commandResult.getCaptureId());
        assertNotNull(commandResult.getRequestBody());
        assertNotNull(commandResult.getResponseBody());

        verify(command).makeGraphQlCall(eq(DEFINITION_FILE_NAME), any());
        verify(paymentInfoService, never()).getPaymentInstrumentTypeBySnapshotAndOrigin(any(BrainTreePaymentMethodSnapshot.class));
    }

}
