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

/**
 * Returns the proposed `paymentAttributes` applied to the checkout.
 */
function usePaymentMethodAttributes() {
  const {
    paymentMethodAttributes
  } = useApi();
  if (!paymentMethodAttributes) {
    throw new ScopeNotGrantedError('Using payment method attributes requires having checkout extension payments scope granted to your app.');
  }
  return useSubscription(paymentMethodAttributes);
}

/**
 * Returns the values for the specified `paymentAttributes` applied to the checkout.
 *
 * @param keys - An array of attribute keys.
 */
function usePaymentMethodAttributeValues(keys) {
  const attributes = usePaymentMethodAttributes();
  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;
  });
}

/**
 * Returns a function to set payment method attributes.
 */
function useApplyPaymentMethodAttributesChange() {
  const api = useApi();
  if (!api.applyPaymentMethodAttributesChange) {
    throw new ExtensionHasNoMethodError('useApplyPaymentMethodAttributesChange', api.extension.target);
  }
  return api.applyPaymentMethodAttributesChange;
}

export { useApplyPaymentMethodAttributesChange, usePaymentMethodAttributeValues, usePaymentMethodAttributes };
