import { ExtensionHasNoMethodError } from './errors.mjs';
import { useApi } from './api.mjs';
import { useSubscription } from './subscription.mjs';

/**
 * Returns the proposed `attributes` applied to the checkout.
 */
function useAttributes() {
  return useSubscription(useApi().attributes);
}

/**
 * Returns the values for the specified `attributes` applied to the checkout.
 *
 * @param keys - An array of attribute keys.
 */
function useAttributeValues(keys) {
  const attributes = useAttributes();
  if (!attributes.length) {
    return [];
  }
  return keys.map(key => {
    const attribute = attributes.find(attribute => attribute.key === key);
    return attribute === null || attribute === void 0 ? void 0 : attribute.value;
  });
}

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

export { useApplyAttributeChange, useAttributeValues, useAttributes };
