package com.braintree.commands.impl;

import com.braintree.command.request.BrainTreeFindMerchantAccountRequest;
import com.braintree.command.result.BrainTreeFindMerchantAccountResult;
import com.braintree.commands.BrainTreeFindMerchantAccountCommand;
import com.braintreegateway.MerchantAccount;
import com.braintreegateway.exceptions.NotFoundException;
import org.apache.log4j.Logger;

import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNullStandardMessage;


public class DefaultBrainTreeFindMerchantAccountCommand extends
    AbstractCommand<BrainTreeFindMerchantAccountRequest, BrainTreeFindMerchantAccountResult> implements
    BrainTreeFindMerchantAccountCommand {

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

    @Override
    public BrainTreeFindMerchantAccountResult perform(final BrainTreeFindMerchantAccountRequest request) {
        validateParameterNotNullStandardMessage("Find Merchant Request", request);
        final String merchantAccountId = request.getMerchantAccount();
        validateParameterNotNullStandardMessage("merchantAccount", merchantAccountId);
        LOG.info("merchantAccountId: " + merchantAccountId);
        try {
            final MerchantAccount merchantAccount = getBraintreeGateway().merchantAccount().find(merchantAccountId);
            boolean isMerchantAccountExist = merchantAccount != null;
            return new BrainTreeFindMerchantAccountResult(isMerchantAccountExist);
        } catch (final NotFoundException exception) {
            LOG.error("Exception occurred, message: " + exception.getMessage(), exception);
            LOG.error("Can't find Braintree Merchant, merchantAccountId: " + merchantAccountId, exception);
            return new BrainTreeFindMerchantAccountResult(false);
        } catch (final Exception exception) {
            LOG.error("Exception occurred, message: " + exception.getMessage(), exception);
            LOG.error("Error while search for Merchant, merchantAccountId: " + merchantAccountId, exception);
            throw new IllegalArgumentException(exception.getMessage());
        }
    }

}
