import { writable } from "svelte/store";
import { clientFetch } from "$lib/client-fetch";
import type { CWMember } from "$lib/optima-api/modules/cw";

function createCwMembersStore() {
  const { subscribe, set } = writable<CWMember[]>([]);
  let fetched = false;
  let inflight: Promise<void> | null = null;

  return {
    subscribe,

    async load(): Promise<void> {
      if (fetched) return;
      if (inflight) return inflight;

      inflight = (async () => {
        try {
          const json = await clientFetch<{ data: CWMember[] }>(
            "/api/cw/members",
          );
          set(json.data ?? []);
          fetched = true;
        } finally {
          inflight = null;
        }
      })();

      return inflight;
    },

    reset() {
      fetched = false;
      inflight = null;
      set([]);
    },
  };
}

export const cwMembers = createCwMembersStore();
