import CommandActionForm_default from "./CommandActionForm.vue.js";
import { generateUniqueSlug } from "../helpers/generate-unique-slug.js";
import { getOpenApiFromPostman } from "../helpers/get-openapi-from-postman.js";
import PostmanImportPreview_default from "./PostmanImportPreview.vue.js";
import { applyPostmanFolderSelectionChange, applyPostmanRequestSelectionChange, buildPostmanRequestTree, countPostmanRequestLeaves, pathKey, pathKeysToRequestIndexPaths } from "../helpers/postman-request-tree.js";
import PostmanRequestTreeRow_default from "./PostmanRequestTreeRow.vue.js";
import { getPostmanDocumentDetails } from "../helpers/get-postman-document-details.js";
import { getCollidingPostmanRequestPathKeys } from "../helpers/postman-request-collisions.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, defineComponent, openBlock, ref, renderList, unref, watch, withCtx } from "vue";
import { useLoadingState } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
//#region src/v2/features/command-palette/components/CommandPaletteImportPostman.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex min-h-0 min-w-0 flex-1 flex-col gap-1.5 overflow-hidden" };
var CommandPaletteImportPostman_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	name: "CommandPaletteImportPostman",
	props: {
		workspaceStore: {},
		eventBus: {},
		inputValue: { default: "" }
	},
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const { toast } = useToasts();
		const loader = useLoadingState();
		/** Document name to merge imported operations into. */
		const importTargetDocumentName = ref(null);
		const baseDocument = ref(null);
		watch(importTargetDocumentName, async (value) => {
			if (!value) {
				baseDocument.value = null;
				return;
			}
			baseDocument.value = await __props.workspaceStore.getEditableDocument(value.slug);
		});
		const mergeSamePathAndMethod = ref(false);
		const postmanDocumentDetails = computed(() => getPostmanDocumentDetails(__props.inputValue));
		const postmanRequestTree = computed(() => buildPostmanRequestTree(postmanDocumentDetails.value?.collection ?? []));
		/** Path keys to import from the Postman collection. */
		const importPathKeys = ref([]);
		const onPostmanRequestSelectionChange = (key, selected) => {
			importPathKeys.value = applyPostmanRequestSelectionChange(importPathKeys.value, key, selected);
		};
		const onPostmanFolderSelectionChange = (node, selected) => {
			importPathKeys.value = applyPostmanFolderSelectionChange(importPathKeys.value, node, selected);
		};
		const collisionsPathKeys = computed(() => {
			return getCollidingPostmanRequestPathKeys(postmanDocumentDetails.value?.collection ?? [], importPathKeys.value, baseDocument.value ?? void 0);
		});
		/** Navigate to a document in the workspace. */
		const navigateToDocument = (documentName) => {
			__props.eventBus.emit("ui:navigate", {
				page: "document",
				path: "overview",
				documentSlug: documentName
			});
		};
		/** Handle import error. */
		const handleImportError = async (errorMessage) => {
			console.error(errorMessage);
			toast(errorMessage, "error");
			await loader.invalidate();
			emit("close");
		};
		/** Handle import. */
		const handleImport = async () => {
			loader.start();
			const mergeTarget = importTargetDocumentName.value?.slug ?? "";
			const mergeIntoExisting = mergeTarget.length > 0 && __props.workspaceStore.workspace.documents[mergeTarget] !== void 0;
			const options = {
				document: (mergeIntoExisting ? await __props.workspaceStore.getEditableDocument(mergeTarget) : null) ?? void 0,
				mergeOperation: mergeSamePathAndMethod.value,
				requestIndexPaths: pathKeysToRequestIndexPaths(importPathKeys.value)
			};
			const document = getOpenApiFromPostman(__props.inputValue ?? "", options);
			if (document === null) return handleImportError("Failed to convert Postman collection to OpenAPI document. Please contact support.");
			if (mergeIntoExisting) {
				await __props.workspaceStore.replaceDocument(mergeTarget, document);
				await loader.validate();
				navigateToDocument(mergeTarget);
				emit("close");
				return;
			}
			const slug = await generateUniqueSlug(document.info?.title ?? "default", new Set(Object.keys(__props.workspaceStore.workspace.documents)));
			if (!slug) return handleImportError("Failed to generate a unique slug for the imported document. Please contact support.");
			await __props.workspaceStore.addDocument({
				name: slug,
				document
			});
			await loader.validate();
			navigateToDocument(slug);
			emit("close");
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				loader: unref(loader),
				onSubmit: handleImport
			}, {
				submit: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Import Postman Collection ", -1)])]),
				default: withCtx(() => [createElementVNode("div", _hoisted_1, [_cache[2] || (_cache[2] = createElementVNode("div", { class: "flex shrink-0 justify-between" }, [createElementVNode("div", { class: "text-c-2 min-h-7 w-full py-1.5 pl-12 text-center text-xs" }, " Postman collection ")], -1)), postmanDocumentDetails.value ? (openBlock(), createBlock(PostmanImportPreview_default, {
					key: 0,
					mergeSamePathAndMethod: mergeSamePathAndMethod.value,
					"onUpdate:mergeSamePathAndMethod": _cache[0] || (_cache[0] = ($event) => mergeSamePathAndMethod.value = $event),
					selectedTargetDocument: importTargetDocumentName.value,
					"onUpdate:selectedTargetDocument": _cache[1] || (_cache[1] = ($event) => importTargetDocumentName.value = $event),
					availableTargetDocuments: Object.entries(__props.workspaceStore.workspace.documents).map(([slug, document]) => ({
						slug,
						label: document.info?.title ?? slug
					})),
					hasCollisionPathKeys: collisionsPathKeys.value.length > 0,
					schema: postmanDocumentDetails.value?.schemaLabel ?? void 0,
					title: postmanDocumentDetails.value?.title ?? "",
					totalRequests: unref(countPostmanRequestLeaves)(postmanDocumentDetails.value?.collection ?? []),
					version: postmanDocumentDetails.value?.version ?? ""
				}, {
					treePicker: withCtx(() => [(openBlock(true), createElementBlock(Fragment, null, renderList(postmanRequestTree.value, (node) => {
						return openBlock(), createBlock(PostmanRequestTreeRow_default, {
							key: unref(pathKey)(node.path),
							collisionPathKeys: collisionsPathKeys.value,
							mergeSamePathAndMethod: mergeSamePathAndMethod.value,
							node,
							selectedKeys: importPathKeys.value,
							onFolderSelectionChange: onPostmanFolderSelectionChange,
							onRequestSelectionChange: onPostmanRequestSelectionChange
						}, null, 8, [
							"collisionPathKeys",
							"mergeSamePathAndMethod",
							"node",
							"selectedKeys"
						]);
					}), 128))]),
					_: 1
				}, 8, [
					"mergeSamePathAndMethod",
					"selectedTargetDocument",
					"availableTargetDocuments",
					"hasCollisionPathKeys",
					"schema",
					"title",
					"totalRequests",
					"version"
				])) : createCommentVNode("", true)])]),
				_: 1
			}, 8, ["loader"]);
		};
	}
});
//#endregion
export { CommandPaletteImportPostman_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=CommandPaletteImportPostman.vue.script.js.map