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

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

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

export { useAppliedGiftCards, useApplyGiftCardChange };
