import { useWorkspace } from "../../../../store/store.js";
import ViewLayoutCollapse_default from "../../../../components/ViewLayout/ViewLayoutCollapse.vue.js";
import { formatComplexScheme, formatScheme, getSchemeOptions, getSecurityRequirements } from "../../libs/auth.js";
import DeleteRequestAuthModal_default from "./DeleteRequestAuthModal.vue.js";
import RequestAuthDataTable_default from "./RequestAuthDataTable.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, normalizeClass, openBlock, ref, renderSlot, toDisplayString, unref, useId, withCtx, withModifiers } from "vue";
import { ScalarButton, ScalarComboboxMultiselect, ScalarIconButton, ScalarListboxCheckbox, useModal } from "@scalar/components";
import { isDefined } from "@scalar/oas-utils/helpers";
import { CLIENT_LS_KEYS, safeLocalStorage } from "@scalar/helpers/object/local-storage";
import { ScalarIconCaretDown, ScalarIconTrash } from "@scalar/icons";
//#region src/views/Request/RequestSection/RequestAuth/RequestAuth.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["id"];
var _hoisted_2 = { class: "flex flex-1" };
var _hoisted_3 = { class: "min-w-0 flex-1 truncate" };
var RequestAuth_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "RequestAuth",
	props: {
		collection: {},
		isReadOnly: {
			type: Boolean,
			default: false
		},
		environment: {},
		envVariables: {},
		layout: {},
		operation: {},
		persistAuth: {
			type: Boolean,
			default: false
		},
		selectedSecuritySchemeUids: {},
		server: {},
		title: {},
		workspace: {}
	},
	emits: ["authorized", "activeSchemes"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const { securitySchemes, securitySchemeMutators, requestMutators, collectionMutators } = useWorkspace();
		const titleId = useId();
		const comboboxButtonRef = ref(null);
		const deleteSchemeModal = useModal();
		const selectedScheme = ref(null);
		const isViewLayoutOpen = ref(false);
		/** Security requirements for the request */
		const securityRequirements = computed(() => {
			const requirements = getSecurityRequirements(__props.operation, __props.collection);
			return {
				filteredRequirements: requirements.filter((r) => Object.keys(r).length),
				requirements
			};
		});
		/** Indicates if auth is required */
		const authIndicator = computed(() => {
			const { filteredRequirements, requirements } = securityRequirements.value;
			if (!requirements.length) return null;
			const isOptional = !requirements.some((req) => Object.keys(req).length > 1) && filteredRequirements.length < requirements.length;
			return {
				icon: isOptional ? "Unlock" : "Lock",
				text: isOptional ? "Optional" : "Required"
			};
		});
		/**
		* Currently selected auth schemes on the collection, we store complex auth joined by a comma to represent the array
		* in the string
		*/
		const selectedSchemeOptions = computed(() => __props.selectedSecuritySchemeUids.map((s) => {
			if (Array.isArray(s)) return formatComplexScheme(s, securitySchemes);
			const scheme = securitySchemes[s ?? ""];
			if (!scheme) return;
			return formatScheme(scheme);
		}).filter(isDefined));
		/** Update the selected auth types */
		function updateSelectedAuth(entries) {
			const addNewOption = entries.find((e) => e.payload);
			const _entries = entries.filter((e) => !e.payload).map(({ id }) => {
				const arr = id.split(",");
				return arr.length > 1 ? arr : id;
			});
			if (addNewOption?.payload) {
				const scheme = securitySchemeMutators.add(addNewOption.payload, __props.collection?.uid);
				if (scheme) _entries.push(scheme.uid);
			}
			editSelectedSchemeUids(_entries);
		}
		const editSelectedSchemeUids = (uids) => {
			if (__props.collection.useCollectionSecurity) {
				collectionMutators.edit(__props.collection.uid, "selectedSecuritySchemeUids", uids);
				if (!__props.persistAuth) return;
				const nameKeys = uids.map((uids) => {
					if (Array.isArray(uids)) return uids.map((uid) => securitySchemes[uid]?.nameKey);
					return securitySchemes[uids]?.nameKey;
				});
				safeLocalStorage().setItem(CLIENT_LS_KEYS.SELECTED_SECURITY_SCHEMES, JSON.stringify(nameKeys));
			} else if (__props.operation?.uid) requestMutators.edit(__props.operation.uid, "selectedSecuritySchemeUids", uids);
		};
		function handleDeleteScheme({ id, label }) {
			selectedScheme.value = {
				id,
				label
			};
			deleteSchemeModal.show();
		}
		const unselectAuth = (unSelectUid) => {
			if (!unSelectUid) return;
			editSelectedSchemeUids(__props.selectedSecuritySchemeUids.filter((uid) => {
				const arr = unSelectUid.split(",");
				if (arr.length > 1 && Array.isArray(uid) && arr.length === uid.length) return uid.every((u) => !arr.includes(u));
				return uid !== unSelectUid;
			}));
			comboboxButtonRef.value?.$el.focus();
			deleteSchemeModal.hide();
		};
		/** Options for the security scheme dropdown */
		const schemeOptions = computed(() => getSchemeOptions(securityRequirements.value.filteredRequirements, __props.collection?.securitySchemes ?? [], securitySchemes, __props.isReadOnly));
		const openAuthCombobox = (event) => {
			if (isViewLayoutOpen.value) event.stopPropagation();
			comboboxButtonRef.value?.$el.click();
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(ViewLayoutCollapse_default, {
				class: "group/params relative",
				itemCount: selectedSchemeOptions.value.length,
				layout: __props.layout,
				"onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => isViewLayoutOpen.value = $event)
			}, {
				title: withCtx(() => [createElementVNode("div", {
					id: unref(titleId),
					class: "inline-flex items-center gap-0.5 leading-[20px]"
				}, [createElementVNode("span", null, toDisplayString(__props.title), 1), authIndicator.value ? (openBlock(), createElementBlock("span", {
					key: 0,
					class: normalizeClass(["text-c-3 hover:bg-b-3 hover:text-c-1 -mr-1 cursor-pointer rounded px-1 py-0.5 text-xs leading-[normal]", { "text-c-1": authIndicator.value.text === "Required" }]),
					onClick: openAuthCombobox
				}, toDisplayString(authIndicator.value.text), 3)) : createCommentVNode("", true)], 8, _hoisted_1)]),
				actions: withCtx(() => [createElementVNode("div", _hoisted_2, [createVNode(unref(ScalarComboboxMultiselect), {
					class: "w-72 text-xs",
					modelValue: selectedSchemeOptions.value,
					multiple: "",
					options: schemeOptions.value,
					placement: "bottom-end",
					teleport: "",
					onDelete: handleDeleteScheme,
					"onUpdate:modelValue": updateSelectedAuth
				}, {
					option: withCtx(({ option, selected }) => [
						createVNode(unref(ScalarListboxCheckbox), {
							multiselect: "",
							selected
						}, null, 8, ["selected"]),
						createElementVNode("div", _hoisted_3, toDisplayString(option.label), 1),
						option.isDeletable ?? !__props.isReadOnly ? (openBlock(), createBlock(unref(ScalarIconButton), {
							key: 0,
							class: "-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100",
							icon: unref(ScalarIconTrash),
							label: `Delete ${option.label}`,
							size: "xs",
							onClick: withModifiers(($event) => handleDeleteScheme(option), ["stop"])
						}, null, 8, [
							"icon",
							"label",
							"onClick"
						])) : createCommentVNode("", true)
					]),
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						ref_key: "comboboxButtonRef",
						ref: comboboxButtonRef,
						"aria-describedby": unref(titleId),
						class: "group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal transition-transform",
						variant: "ghost"
					}, {
						default: withCtx(() => [selectedSchemeOptions.value.length === 1 ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [_cache[5] || (_cache[5] = createElementVNode("span", { class: "sr-only" }, "Selected Auth Type:", -1)), createTextVNode(" " + toDisplayString(selectedSchemeOptions.value[0]?.label), 1)], 64)) : selectedSchemeOptions.value.length > 1 ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [_cache[6] || (_cache[6] = createTextVNode(" Multiple ", -1)), _cache[7] || (_cache[7] = createElementVNode("span", { class: "sr-only" }, "Auth Types Selected", -1))], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [_cache[8] || (_cache[8] = createElementVNode("span", { class: "sr-only" }, "Select", -1)), _cache[9] || (_cache[9] = createTextVNode(" Auth Type ", -1))], 64)), createVNode(unref(ScalarIconCaretDown), {
							class: "size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180",
							weight: "bold"
						})]),
						_: 1
					}, 8, ["aria-describedby"])]),
					_: 1
				}, 8, ["modelValue", "options"])])]),
				default: withCtx(() => [createVNode(RequestAuthDataTable_default, {
					collection: __props.collection,
					envVariables: __props.envVariables,
					environment: __props.environment,
					layout: __props.layout,
					persistAuth: __props.persistAuth,
					selectedSchemeOptions: selectedSchemeOptions.value,
					server: __props.server,
					workspace: __props.workspace,
					onActiveSchemes: _cache[0] || (_cache[0] = ($event) => emits("activeSchemes", $event)),
					onAuthorized: _cache[1] || (_cache[1] = ($event) => emits("authorized"))
				}, {
					"oauth-actions": withCtx(() => [renderSlot(_ctx.$slots, "oauth-actions", {}, void 0, true)]),
					_: 3
				}, 8, [
					"collection",
					"envVariables",
					"environment",
					"layout",
					"persistAuth",
					"selectedSchemeOptions",
					"server",
					"workspace"
				]), createVNode(DeleteRequestAuthModal_default, {
					scheme: selectedScheme.value,
					state: unref(deleteSchemeModal),
					onClose: _cache[2] || (_cache[2] = ($event) => unref(deleteSchemeModal).hide()),
					onDelete: _cache[3] || (_cache[3] = ($event) => unselectAuth(selectedScheme.value?.id))
				}, null, 8, ["scheme", "state"])]),
				_: 3
			}, 8, ["itemCount", "layout"]);
		};
	}
});
//#endregion
export { RequestAuth_vue_vue_type_script_setup_true_lang_default as default };

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