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

class ExtensionHasNoTargetError extends Error {
  constructor(target) {
    super(`Cannot call 'useTarget()' on target '${target}'. Property 'target' is not found on api.`);
    this.name = 'ExtensionHasNoTargetError';
  }
}

/**
 * Returns the cart line the extension is attached to. This hook can only be used by extensions in the
 * `purchase.cart-line-item.line-components.render` and `customer-account.order-status.cart-line-item.render-after`
 * extension targets. Until version `2023-04`, this hook returned a `PresentmentCartLine` object.
 */
function useTarget() {
  const api = useApi();
  if (!api.target) {
    throw new ExtensionHasNoTargetError(api.extension.target);
  }
  return useSubscription(api.target);
}

export { useTarget };
