import { __toESM } from "../_virtual/rolldown_runtime.js";
import { SseClientEvents } from "../events/sse-client-events.js";
import { eventBus } from "../services/eventEmitter.js";
import "../services/index.js";
import { useStudio } from "./StudioProvider.js";
import { require_debounce } from "../node_modules/lodash/debounce.js";
import { getDocumentsCacheKey } from "../hooks/useDocuments.js";
import { getNamespacesByPipelineCacheKey } from "../hooks/useNamespaces.js";
import { getWorkflowCacheKey, getWorkflowsByPipelineCacheKey, getWorkflowsCacheKey } from "../hooks/useWorkflows.js";
import { c } from "react/compiler-runtime";
import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
var import_debounce = /* @__PURE__ */ __toESM(require_debounce(), 1), DEBOUNCE_MS = 300;
function createDebouncedInvalidator(e, u) {
	return (0, import_debounce.default)(() => {
		e.invalidateQueries({ queryKey: u });
	}, DEBOUNCE_MS);
}
function InvalidationEventsProvider() {
	let e = c(5), { environment: f } = useStudio(), _ = useQueryClient(), v;
	e[0] === Symbol.for("react.memo_cache_sentinel") ? (v = /* @__PURE__ */ new Map(), e[0] = v) : v = e[0];
	let y = useRef(v), b, x;
	return e[1] !== f.id || e[2] !== _ ? (b = () => {
		if (!f.id) return;
		let e = f.id, d = y.current, p = function(e) {
			let u = JSON.stringify(e);
			d.has(u) || d.set(u, createDebouncedInvalidator(_, e)), d.get(u)();
		}, m = eventBus.on(SseClientEvents.WORKFLOW_CREATED, (u) => {
			u.namespaceId && p(getWorkflowsCacheKey(e, u.namespaceId)), u.pipelineId && (p(getNamespacesByPipelineCacheKey(e, u.pipelineId)), p(getWorkflowsByPipelineCacheKey(e, u.pipelineId)));
		}), h = eventBus.on(SseClientEvents.WORKFLOW_UPDATED, (u) => {
			u.id && p(getWorkflowCacheKey(e, u.id)), u.namespaceId && p(getWorkflowsCacheKey(e, u.namespaceId)), u.pipelineId && (p(getNamespacesByPipelineCacheKey(e, u.pipelineId)), p(getWorkflowsByPipelineCacheKey(e, u.pipelineId)));
		}), g = eventBus.on(SseClientEvents.DOCUMENT_CREATED, (u) => {
			u.workflowId && p(getDocumentsCacheKey(e, u.workflowId));
		});
		return () => {
			m(), h(), g(), d.forEach(_temp), d.clear();
		};
	}, x = [_, f.id], e[1] = f.id, e[2] = _, e[3] = b, e[4] = x) : (b = e[3], x = e[4]), useEffect(b, x), null;
}
function _temp(e) {
	return e.cancel();
}
export { InvalidationEventsProvider };
