import DataTableRow_default from "../../../../components/DataTable/DataTableRow.vue.js";
import { getEnvironmentVariables } from "../../operation-block/helpers/get-environment-variables.js";
import OAuthScopesInput_default from "./OAuthScopesInput.vue.js";
import { authorizeOauth2 } from "../helpers/oauth.js";
import RequestAuthDataTableInput_default from "./RequestAuthDataTableInput.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, openBlock, ref, unref, watch, withCtx } from "vue";
import { ScalarButton, useLoadingState } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { pkceOptions } from "@scalar/oas-utils/entities/spec";
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex h-8 items-center justify-end gap-2 border-t" };
var _hoisted_2 = { class: "flex h-8 w-full items-center justify-end border-t" };
/** We filter selected scopes to only include scopes that are in this flow*/
var OAuth2_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "OAuth2",
	props: {
		environment: {},
		flows: {},
		type: {},
		selectedScopes: {},
		scheme: {},
		server: {},
		proxyUrl: {},
		name: {},
		eventBus: {}
	},
	emits: ["update:selectedScopes"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const loader = useLoadingState();
		const { toast } = useToasts();
		/** The current OAuth flow based on the selected type */
		const flow = computed(() => __props.flows[__props.type]);
		const selectedScopes = computed(() => __props.selectedScopes.filter((scope) => scope in (flow.value.scopes ?? {})));
		/** Updates the security scheme base */
		const handleOauth2Update = (payload) => {
			if (__props.scheme.type === "openIdConnect") return handleOauth2SecretsUpdate(payload);
			__props.eventBus.emit("auth:update:security-scheme", {
				payload: {
					type: __props.scheme.type,
					flows: { [__props.type]: payload }
				},
				name: __props.name
			});
		};
		/** Updates the flow secrets */
		const handleOauth2SecretsUpdate = (payload) => __props.eventBus.emit("auth:update:security-scheme-secrets", {
			payload: {
				type: __props.scheme.type,
				[__props.type]: payload
			},
			name: __props.name
		});
		/** Clears the flow secrets */
		const clearOauth2Secrets = () => __props.eventBus.emit("auth:clear:security-scheme-secrets", { name: __props.name });
		/** Track if we have set the redirect uri */
		const hasPrefilledRedirectUri = ref(false);
		/** Default the redirect-uri to the current origin if we have access to window */
		watch(() => flow.value["x-scalar-secret-redirect-uri"], (newRedirectUri) => {
			if (hasPrefilledRedirectUri.value || newRedirectUri || typeof window === "undefined" || !("x-scalar-secret-redirect-uri" in flow.value)) return;
			hasPrefilledRedirectUri.value = true;
			handleOauth2SecretsUpdate({ "x-scalar-secret-redirect-uri": window.location.origin + window.location.pathname });
		}, { immediate: true });
		/**
		* Authorizes the user using the specified OAuth flow.
		* Opens the appropriate OAuth dialog and/or performs the token exchange.
		*/
		const handleAuthorize = async () => {
			if (loader.isLoading) return;
			loader.start();
			const [error, tokens] = await authorizeOauth2(__props.flows, __props.type, selectedScopes.value, __props.server, __props.proxyUrl, getEnvironmentVariables(__props.environment));
			await loader.clear();
			if (tokens?.accessToken) handleOauth2SecretsUpdate({
				"x-scalar-secret-token": tokens.accessToken,
				...tokens.refreshToken ? { "x-scalar-secret-refresh-token": tokens.refreshToken } : {}
			});
			else {
				console.error(error);
				toast(error?.message ?? "Failed to authorize", "error");
			}
		};
		/** Updates the secret location */
		const handleSecretLocationUpdate = (value) => {
			const credentialsLocation = value === "body" ? "body" : "header";
			if (__props.scheme.type !== "openIdConnect") handleOauth2Update({ "x-scalar-credentials-location": credentialsLocation });
			handleOauth2SecretsUpdate({ "x-scalar-credentials-location": credentialsLocation });
		};
		return (_ctx, _cache) => {
			return Boolean(flow.value["x-scalar-secret-token"]) ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createVNode(unref(DataTableRow_default), null, {
				default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
					class: "border-r-transparent",
					environment: __props.environment,
					modelValue: flow.value["x-scalar-secret-token"],
					placeholder: "QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT",
					type: "password",
					"onUpdate:modelValue": _cache[0] || (_cache[0] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-token": v }))
				}, {
					default: withCtx(() => [..._cache[12] || (_cache[12] = [createTextVNode(" Access Token ", -1)])]),
					_: 1
				}, 8, ["environment", "modelValue"])]),
				_: 1
			}), createVNode(unref(DataTableRow_default), { class: "min-w-full" }, {
				default: withCtx(() => [createElementVNode("div", _hoisted_1, [createVNode(unref(ScalarButton), {
					class: "mr-1 p-0 px-2 py-0.5",
					loader: unref(loader),
					size: "sm",
					variant: "outlined",
					onClick: _cache[1] || (_cache[1] = () => handleOauth2SecretsUpdate({
						"x-scalar-secret-token": "",
						"x-scalar-secret-refresh-token": ""
					}))
				}, {
					default: withCtx(() => [..._cache[13] || (_cache[13] = [createTextVNode(" Clear ", -1)])]),
					_: 1
				}, 8, ["loader"])])]),
				_: 1
			})], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => ["authorizationUrl" in flow.value ? (openBlock(), createBlock(RequestAuthDataTableInput_default, {
						key: 0,
						containerClass: "border-r-0",
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-auth-url"] ?? "",
						placeholder: "https://galaxy.scalar.com/authorize",
						"onUpdate:modelValue": _cache[2] || (_cache[2] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-auth-url": v });
							handleOauth2Update({ authorizationUrl: v });
						})
					}, {
						default: withCtx(() => [..._cache[14] || (_cache[14] = [createTextVNode(" Auth URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])) : createCommentVNode("", true), "tokenUrl" in flow.value ? (openBlock(), createBlock(RequestAuthDataTableInput_default, {
						key: 1,
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-token-url"] ?? "",
						placeholder: "https://galaxy.scalar.com/token",
						"onUpdate:modelValue": _cache[3] || (_cache[3] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-token-url": v });
							handleOauth2Update({ tokenUrl: v });
						})
					}, {
						default: withCtx(() => [..._cache[15] || (_cache[15] = [createTextVNode(" Token URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])) : createCommentVNode("", true)]),
					_: 1
				}),
				"x-scalar-secret-redirect-uri" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 0 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-redirect-uri"],
						placeholder: "https://galaxy.scalar.com/callback",
						"onUpdate:modelValue": _cache[4] || (_cache[4] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-redirect-uri": v });
						})
					}, {
						default: withCtx(() => [..._cache[16] || (_cache[16] = [createTextVNode(" Redirect URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				"x-scalar-secret-username" in flow.value && "x-scalar-secret-password" in flow.value ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						class: "text-c-2",
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-username"],
						placeholder: "janedoe",
						"onUpdate:modelValue": _cache[5] || (_cache[5] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-username": v }))
					}, {
						default: withCtx(() => [..._cache[17] || (_cache[17] = [createTextVNode(" Username ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				}), createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-password"],
						placeholder: "********",
						type: "password",
						"onUpdate:modelValue": _cache[6] || (_cache[6] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-password": v }))
					}, {
						default: withCtx(() => [..._cache[18] || (_cache[18] = [createTextVNode(" Password ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})], 64)) : createCommentVNode("", true),
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-client-id"],
						placeholder: "12345",
						"onUpdate:modelValue": _cache[7] || (_cache[7] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-client-id": v }))
					}, {
						default: withCtx(() => [..._cache[19] || (_cache[19] = [createTextVNode(" Client ID ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				}),
				"x-scalar-secret-client-secret" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 2 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-client-secret"],
						placeholder: "XYZ123",
						type: "password",
						"onUpdate:modelValue": _cache[8] || (_cache[8] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-client-secret": v }))
					}, {
						default: withCtx(() => [..._cache[20] || (_cache[20] = [createTextVNode(" Client Secret ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				"x-usePkce" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 3 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						enum: unref(pkceOptions),
						environment: __props.environment,
						modelValue: flow.value["x-usePkce"],
						readOnly: "",
						"onUpdate:modelValue": _cache[9] || (_cache[9] = (v) => handleOauth2Update({ "x-usePkce": v }))
					}, {
						default: withCtx(() => [..._cache[21] || (_cache[21] = [createTextVNode(" Use PKCE ", -1)])]),
						_: 1
					}, 8, [
						"enum",
						"environment",
						"modelValue"
					])]),
					_: 1
				})) : createCommentVNode("", true),
				__props.type !== "implicit" ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 4 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						enum: ["header", "body"],
						environment: __props.environment,
						modelValue: flow.value["x-scalar-credentials-location"] || "header",
						placeholder: "header",
						readOnly: "",
						"onUpdate:modelValue": _cache[10] || (_cache[10] = (v) => handleSecretLocationUpdate(v))
					}, {
						default: withCtx(() => [..._cache[22] || (_cache[22] = [createTextVNode(" Credentials Location ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(OAuthScopesInput_default, {
						flow: flow.value,
						flowType: __props.type,
						selectedScopes: selectedScopes.value,
						"onUpdate:selectedScopes": _cache[11] || (_cache[11] = (v) => emits("update:selectedScopes", v))
					}, null, 8, [
						"flow",
						"flowType",
						"selectedScopes"
					])]),
					_: 1
				}),
				createVNode(unref(DataTableRow_default), { class: "min-w-full" }, {
					default: withCtx(() => [createElementVNode("div", _hoisted_2, [__props.scheme.type === "openIdConnect" ? (openBlock(), createBlock(unref(ScalarButton), {
						key: 0,
						class: "mr-1 p-0 px-2 py-0.5",
						loader: unref(loader),
						size: "sm",
						variant: "outlined",
						onClick: clearOauth2Secrets
					}, {
						default: withCtx(() => [..._cache[23] || (_cache[23] = [createTextVNode(" Clear ", -1)])]),
						_: 1
					}, 8, ["loader"])) : createCommentVNode("", true), createVNode(unref(ScalarButton), {
						class: "mr-0.75 p-0 px-2 py-0.5",
						loader: unref(loader),
						size: "sm",
						variant: "outlined",
						onClick: handleAuthorize
					}, {
						default: withCtx(() => [..._cache[24] || (_cache[24] = [createTextVNode(" Authorize ", -1)])]),
						_: 1
					}, 8, ["loader"])])]),
					_: 1
				})
			], 64));
		};
	}
});
//#endregion
export { OAuth2_vue_vue_type_script_setup_true_lang_default as default };

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