import { initBgIntervalProcess } from "../bg-interval.js";
import { withWrite } from "../with-transactions.js";
import { getClientGroups, clientGroupHasPendingMutations, setClientGroups } from "./client-groups.js";
import { getClients } from "./clients.js";
const GC_INTERVAL_MS = 5 * 60 * 1e3;
let latestGCUpdate;
function initClientGroupGC(dagStore, enableMutationRecovery, lc, signal) {
  initBgIntervalProcess(
    "ClientGroupGC",
    () => {
      latestGCUpdate = gcClientGroups(dagStore, enableMutationRecovery);
      return latestGCUpdate;
    },
    () => GC_INTERVAL_MS,
    lc,
    signal
  );
}
function gcClientGroups(dagStore, enableMutationRecovery) {
  return withWrite(dagStore, async (tx) => {
    const clients = await getClients(tx);
    const clientGroupIDs = /* @__PURE__ */ new Set();
    for (const client of clients.values()) {
      clientGroupIDs.add(client.clientGroupID);
    }
    const clientGroups = /* @__PURE__ */ new Map();
    const removeClientGroups = /* @__PURE__ */ new Set();
    for (const [clientGroupID, clientGroup] of await getClientGroups(tx)) {
      if (clientGroupIDs.has(clientGroupID) || enableMutationRecovery && clientGroupHasPendingMutations(clientGroup)) {
        clientGroups.set(clientGroupID, clientGroup);
      } else {
        removeClientGroups.add(clientGroupID);
      }
    }
    await setClientGroups(clientGroups, tx);
    return clientGroups;
  });
}
export {
  gcClientGroups,
  initClientGroupGC
};
//# sourceMappingURL=client-group-gc.js.map
