package com.braintree.graphql.commands.impl;

import com.braintree.command.result.BrainTreeSubscriptionResult;
import com.braintree.commands.impl.AbstractCommand;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeCreateCustomerInput;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeCustomerInput;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeCreateCustomerPayload;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeCustomer;
import com.braintreegateway.ValidationError;
import de.hybris.platform.payment.AdapterException;
import de.hybris.platform.payment.commands.CreateSubscriptionCommand;
import de.hybris.platform.payment.commands.request.CreateSubscriptionRequest;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.braintree.constants.BraintreeConstants.INPUT_PARAMETER;
import static com.braintree.constants.BraintreeConstants.RESULT_DATA;
import static com.braintree.constants.BraintreeConstants.RESULT_ERRORS;

public class DefaultBrainTreeGraphQLCreateSubscriptionCommand extends AbstractCommand implements
        CreateSubscriptionCommand {

    private static final Logger LOG = Logger.getLogger(DefaultBrainTreeGraphQLCreateSubscriptionCommand.class);

    private static final String DEFINITION_FILE_NAME = "createCustomer";
    private static final String MUTATION_NAME = "createCustomer";
    private static final String ERROR_DURING_CUSTOMER_CREATION_MESSAGE = "[BT Create Customer] Error during customer creation!";

    @Override
    public BrainTreeSubscriptionResult perform(CreateSubscriptionRequest createSubscriptionRequest) {

        try {
            Map<String, Object> result = makeGraphQlCall(DEFINITION_FILE_NAME,
                    createVariablesMap(createSubscriptionRequest));
            ArrayList<Map<String, Object>> mapErrors = (ArrayList<Map<String, Object>>) result.get(RESULT_ERRORS);

            if (mapErrors == null) {
                return translateResponse((Map<String, Object>) result.get(RESULT_DATA));
            } else {
                List<ValidationError> errors = mapErrors.stream()
                        .map(stringObjectMap -> objectMapper.convertValue(stringObjectMap, ValidationError.class))
                        .collect(Collectors.toList());
                getLoggingHandler().handleValidationErrors(errors);
                throw new IllegalArgumentException();
            }

        } catch (final Exception exception) {
            LOG.error(ERROR_DURING_CUSTOMER_CREATION_MESSAGE);
            throw new AdapterException(exception.getMessage(), exception);
        }
    }

    private BrainTreeSubscriptionResult translateResponse(Map<String, Object> data) {

        final BrainTreeSubscriptionResult result = new BrainTreeSubscriptionResult();
        result.setTransactionStatus(TransactionStatus.REJECTED);

        BrainTreeCreateCustomerPayload payload = objectMapper
                .convertValue(data.get(MUTATION_NAME), BrainTreeCreateCustomerPayload.class);

        BrainTreeCustomer customer;

        if (payload != null) {
            customer = payload.getCustomer();
            if (customer != null) {
                result.setMerchantTransactionCode(customer.getLegacyId());
                result.setRequestId(customer.getLegacyId());
                result.setGraphQLId(customer.getId());
                result.setTransactionStatus(TransactionStatus.ACCEPTED);
                result.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL);
                getLoggingHandler().handleResult(customer);
            }
        }

        return result;
    }

    private Map<String, Object> createVariablesMap(final CreateSubscriptionRequest request) {

        Map<String, Object> map = new HashMap<>();

        BrainTreeCreateCustomerInput input = new BrainTreeCreateCustomerInput();
        BrainTreeCustomerInput customer = new BrainTreeCustomerInput();

        customer.setEmail(request.getBillingInfo().getEmail());
        customer.setFirstName(request.getBillingInfo().getFirstName());
        customer.setLastName(request.getBillingInfo().getLastName());

        input.setCustomer(customer);

        map.put(INPUT_PARAMETER, input);

        return map;
    }

}
