import {
  fetchAllCursorPagesMainThread,
  type CursorFetchRequest,
  type CursorPageResponse,
} from "./cursorFetchCore";

type CursorWorkerRequestMessage = {
  id: string;
  request: CursorFetchRequest;
};

type CursorWorkerResponseMessage<TItem> =
  | {
      id: string;
      ok: true;
      response: CursorPageResponse<TItem>;
    }
  | {
      id: string;
      ok: false;
      error: string;
    };

self.addEventListener("message", async (event: MessageEvent<CursorWorkerRequestMessage>) => {
  const { id, request } = event.data;

  try {
    const response = await fetchAllCursorPagesMainThread(request);
    self.postMessage({
      id,
      ok: true,
      response,
    } satisfies CursorWorkerResponseMessage<unknown>);
  } catch (error) {
    self.postMessage({
      id,
      ok: false,
      error: error instanceof Error ? error.message : String(error),
    } satisfies CursorWorkerResponseMessage<unknown>);
  }
});

export {};
