'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var hooks = require('preact/hooks');
var errors = require('./errors.js');
var api = require('./api.js');
var subscription = require('./subscription.js');

/**
 * Returns the metafields configured with `shopify.ui.extension.toml`.
 * @arg {AppMetafieldFilters} - filter the list of returned metafields
 */
function useAppMetafields(filters = {}) {
  const api$1 = api.useApi();
  const extensionTarget = api$1.extension.target;
  if (!('appMetafields' in api$1)) {
    throw new errors.ExtensionHasNoFieldError('appMetafields', extensionTarget);
  }
  const appMetafields = subscription.useSubscription(api$1.appMetafields);
  return hooks.useMemo(() => {
    if (filters.key && !filters.namespace) {
      throw new errors.CustomerAccountUIExtensionError('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]);
}

exports.useAppMetafields = useAppMetafields;
