import { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useQuery } from '@apollo/client';
import withGraphQL from '../withGraphQL';
import { marketplaceProductDataStore } from '../../store/marketplaceProductData';
import { MARKETPLACE_PRODUCT } from './query/queryProduct';

export const GraphQLAdapter = ({ data }) => {
    const defaultFetchPolicy = 'network-only';
    const {
        data: queryAdapterData,
        loading,
        error
    } = useQuery(
        MARKETPLACE_PRODUCT,
        {
            variables: {
                productId: data.productId,
                currency: data.currency
            },
            fetchPolicy: defaultFetchPolicy
        }
    );

    const { setMarketplaceProductData } = marketplaceProductDataStore();

    const hasQueryData = (queryError, queryLoading, queryData) => (
        !queryError && !queryLoading && queryData
    );

    useEffect(() => {
        if (hasQueryData(error, loading, queryAdapterData)) {
            setMarketplaceProductData(queryAdapterData);
        }
    }, [error, loading, queryAdapterData]);

    return (null);
};

GraphQLAdapter.schema = () => ({
    marketplaceData: {
        adTenant: 'config.channelSettings.partner',
        baseUrl: 'config.channelSettings.channelCanonicalBaseUrl',
        productId: 'application.config.productRefId',
        currency: 'config.currency'
    }
});

GraphQLAdapter.propTypes = {
    data: PropTypes.shape({
        adTenant: PropTypes.string.isRequired,
        baseUrl: PropTypes.string.isRequired,
        productId: PropTypes.string.isRequired
    })
};

GraphQLAdapter.defaultProps = {
    data: {
        adTenant: 'APPDIRECT',
        baseUrl: 'http://localhost:3000',
        productId: 'cf6ab187-628b-4571-8089-d97319d68801'
    }
};

export default withGraphQL(GraphQLAdapter, 'api/graphql/preview');
