export function getCallbackAction(id: string, action: string) {
  return `callback_${action}_${id}`;
}

// eslint-disable-next-line require-await
export async function callIframe(iframe: HTMLIFrameElement, action: string) {
  const callbackAction = getCallbackAction(iframe.dataset.id as string, action);
  const promise = new Promise<{ value: any; action: string }>((resolve) => {
    const handleMessage = ({ data }: MessageEvent) => {
      if (data.action === callbackAction) {
        window.removeEventListener('message', handleMessage);
        resolve(data);
      }
    };
    window.addEventListener('message', handleMessage);
  });
  iframe?.contentWindow?.postMessage({ action, callback: callbackAction }, '*');
  return promise;
}
