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

/**
 * Returns the current discount codes applied to the cart, and automatically re-renders
 * your component if discount codes are added or removed.
 */
function useDiscountCodes() {
  const {
    discountCodes
  } = useApi();
  return useSubscription(discountCodes);
}

/**
 * Returns the current discount allocations applied to the cart, and automatically re-renders
 * your component if discount allocations changed.
 */
function useDiscountAllocations() {
  const {
    discountAllocations
  } = useApi();
  return useSubscription(discountAllocations);
}

/**
 * Returns a function to add or remove discount codes.
 *
 * > Caution:
 * > See [security considerations](https://shopify.dev/docs/api/checkout-ui-extensions/configuration#network-access) if your extension retrieves discount codes through a network call.
 */
function useApplyDiscountCodeChange() {
  const api = useApi();
  if ('applyDiscountCodeChange' in api) {
    return api.applyDiscountCodeChange;
  }
  throw new ExtensionHasNoMethodError('applyDiscountCodeChange', api.extension.target);
}

export { useApplyDiscountCodeChange, useDiscountAllocations, useDiscountCodes };
