import DataLoader from "dataloader";
import React from "react";
import { useWixInstanceService } from "./../../_shared/request-service-provider/wix-instance-context.js";
import { PollsService } from "../services/polls-service.js";
const isSSR = () => typeof window === "undefined";
const getMembersModulePromise = () => {
  return import(
    /* webpackChunkName: "wix-ricos-members" */
    "@wix/members"
  ).then(
    (module) => module.members
  );
};
const fetchMembers = (membersIds, getWixClientPromise) => Promise.all([getWixClientPromise(), getMembersModulePromise()]).then(
  ([wixClient, members]) => wixClient.use(members).queryMembers().in("_id", membersIds).find().then((res) => res.items).catch((e) => {
    console.error("[pollsStrategy] fetchMembers failed. error:", e);
    return [];
  }).then(normalizeMembers)
);
const membersCache = /* @__PURE__ */ new Map();
const createMembersLoader = (loadMembers) => {
  return new DataLoader(
    (memberIds) => {
      return loadMembers(memberIds).then(
        (memberList) => memberIds.map(
          (id) => memberList.find((m) => m.siteMemberId === id) || new Error("Member not found")
        )
      );
    },
    { cacheMap: membersCache }
  );
};
const normalizeMembers = (rawMembers) => rawMembers?.map?.((member) => {
  return {
    siteMemberId: member._id ?? void 0,
    imageUrl: member.profile?.photo?.url ?? void 0,
    name: {
      nick: member.profile?.nickname ?? void 0
    }
  };
});
const createGetSiteMembers = (getWixClientPromise) => {
  if (isSSR()) {
    return void 0;
  }
  const loader = createMembersLoader(async (memberIds) => {
    const members = await fetchMembers(memberIds, getWixClientPromise);
    return memberIds.map(
      (id) => members.find((m) => m.siteMemberId === id) || {
        siteMemberId: id
      }
    );
  });
  return loader.loadMany.bind(loader);
};
const usePollServices = (settings) => {
  const wixInstance = useWixInstanceService();
  const { getWixClientPromise } = wixInstance();
  return React.useMemo(() => {
    if (settings.pollServiceApi || !getWixClientPromise) {
      return settings;
    }
    return {
      ...settings,
      pollServiceApi: new PollsService(getWixClientPromise),
      getSiteMembers: createGetSiteMembers(getWixClientPromise)
    };
  }, [settings, getWixClientPromise]);
};
export {
  usePollServices
};
//# sourceMappingURL=use-poll-services.js.map
