import { RESPONSE } from '@assets/filters/common/events/eventTypes';

export const RESPONSE_EVENT = RESPONSE;

type ResponsePayload = { document: Document } & Record<string, any>;
export type ResponseEventPayload = { response: ResponsePayload };

export function dispatchPreordersResponseEvent(
   responseDocument: Document,
   eventTarget: EventTarget = document,
   callback?: (response: ResponsePayload) => ResponsePayload,
) {
   let response: ResponsePayload = Object.defineProperties({ document: responseDocument }, {
      pagerHtml: { get: () => responseDocument.querySelector('[data-component="pager"]') },
      bottomBarHtml: { get: () => responseDocument.querySelector('[data-component="preorders-bottombar"]') },
      pager: { get: () => ({ total: responseDocument.querySelector('[data-pager-total]')?.textContent }) },
   });

   if (callback) {
      response = callback(response);
   }

   response.filters = [];

   const event = new CustomEvent(RESPONSE_EVENT, {
      bubbles: true,
      detail: { response },
   });

   eventTarget.dispatchEvent(event);
}
