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

/**
 * Returns the proposed `attributes` applied to the checkout.
 */
function useAttributes() {
  const api = useApi();
  const extensionTarget = api.extension.target;
  if (!('attributes' in api)) {
    throw new ExtensionHasNoFieldError('attributes', extensionTarget);
  }
  return useSubscription(api.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 !== null && attributes !== void 0 && 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;
  });
}

export { useAttributeValues, useAttributes };
