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

/**
 * Returns the current array of `metafields` applied to the checkout.
 * You can optionally filter the list.
 * @arg {MetafieldsFilters} - filter the list of returned metafields
 */
function useMetafields(filters) {
  const api = useApi();
  const extensionTarget = api.extension.target;
  if (!('metafields' in api)) {
    throw new ExtensionHasNoFieldError('metafields', extensionTarget);
  }
  const metaFields = useSubscription(api.metafields);
  return useMemo(() => {
    if (filters) {
      const {
        namespace,
        key
      } = filters;
      if (!namespace) {
        throw new CustomerAccountUIExtensionError('You must pass in a namespace with a key');
      }
      const filteredResults = metaFields.filter(metafield => metafield.namespace === namespace && (!key || metafield.key === key));
      return filteredResults;
    }
    return metaFields;
  }, [filters, metaFields]);
}

export { useMetafields };
