package com.braintree.daos.impl;

import com.braintree.daos.BrainTreeAccessTokenDao;
import com.braintree.model.PaypalAccessTokenModel;
import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException;
import de.hybris.platform.servicelayer.internal.dao.AbstractItemDao;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Optional;

public class DefaultBrainTreeAccessTokenDao extends AbstractItemDao implements BrainTreeAccessTokenDao {

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

    private static final String FIND_ACCESS_TOKEN_BY_GUID_QUERY = "SELECT {" + PaypalAccessTokenModel.PK
            + "} FROM {" + PaypalAccessTokenModel._TYPECODE + "} WHERE {" + PaypalAccessTokenModel.GUID + "} = ?guid";
    private static final String GUID = "guid";

    public Optional<PaypalAccessTokenModel> findAccessTokenByGuid(String guid) {
        Map<String, Object> params = Map.of(GUID, guid);
        FlexibleSearchQuery query = new FlexibleSearchQuery(FIND_ACCESS_TOKEN_BY_GUID_QUERY, params);
        Optional<PaypalAccessTokenModel> foundAccessToken = Optional.empty();

        try {
            foundAccessToken = Optional.of(getFlexibleSearchService().searchUnique(query));
        } catch (ModelNotFoundException exception) {
            LOG.error("The BraintreeAccessToken by guid = {} was not found", guid);
        }

        return foundAccessToken;
    }

}
