import { useMemo } from 'preact/hooks';
import { CheckoutUIExtensionError } from './errors.mjs';
import { useApi } from './api.mjs';
import { useSubscription } from './subscription.mjs';

/**
 * Returns the metafields configured with `shopify.extension.toml`.
 * @arg {AppMetafieldFilters} - filter the list of returned metafields
 */
function useAppMetafields(filters = {}) {
  const appMetafields = useSubscription(useApi().appMetafields);
  return useMemo(() => {
    if (filters.key && !filters.namespace) {
      throw new CheckoutUIExtensionError('You must pass in a namespace with a key');
    }
    const filterKeys = Object.keys(filters);
    if (filterKeys.length) {
      return appMetafields.filter(app => {
        return filterKeys.every(key => {
          if (key === 'id' || key === 'type') {
            return app.target[key] === filters[key];
          }
          return app.metafield[key] === filters[key];
        });
      });
    }
    return appMetafields;
  }, [filters, appMetafields]);
}

export { useAppMetafields };
