import { useMemo } from 'preact/hooks';
import { CheckoutUIExtensionError, ExtensionHasNoMethodError } 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 metaFields = useSubscription(useApi().metafields);
  return useMemo(() => {
    if (filters) {
      const {
        namespace,
        key
      } = filters;
      if (!namespace) {
        throw new CheckoutUIExtensionError('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]);
}

/**
 * Returns a function to mutate the `metafields` property of the checkout.
 */
function useApplyMetafieldsChange() {
  const api = useApi();
  if ('applyMetafieldChange' in api) {
    return api.applyMetafieldChange;
  }
  throw new ExtensionHasNoMethodError('applyMetafieldChange', api.extension.target);
}

export { useApplyMetafieldsChange, useMetafields };
