import { ACTIVE_ENTITIES_SYMBOL, createActiveEntitiesStore } from "../store/active-entities.js";
import { CLIENT_CONFIGURATION_SYMBOL } from "../hooks/useClientConfig.js";
import { LAYOUT_SYMBOL } from "../hooks/useLayout.js";
import { SIDEBAR_SYMBOL, createSidebarState } from "../hooks/useSidebar.js";
import { getRequestUidByPathMethod } from "./get-request-uid-by-path-method.js";
import { loadAllResources } from "./local-storage.js";
import { createPluginManager } from "../plugins/plugin-manager.js";
import { PLUGIN_MANAGER_SYMBOL } from "../plugins/hooks/usePluginManager.js";
import { WORKSPACE_SYMBOL, createWorkspaceStore } from "../store/store.js";
import { createApp, ref, watch } from "vue";
import { LS_KEYS } from "@scalar/helpers/object/local-storage";
import { prettyPrintJson } from "@scalar/helpers/json/pretty-print-json";
import { workspaceSchema } from "@scalar/oas-utils/entities/workspace";
import { DATA_VERSION, DATA_VERSION_LS_LEY } from "@scalar/oas-utils/migrations";
import { apiClientConfigurationSchema } from "@scalar/types/api-reference";
//#region src/libs/create-client.ts
/**
* Sync method to create the api client vue app and store
*
* This method will NOT import the spec, just create the modal so you must use update/updateConfig before opening
*/
var createApiClient = ({ el, appComponent, configuration: _configuration = {}, isReadOnly = false, store: _store, persistData = true, mountOnInitialize = true, layout = "desktop", router }) => {
	const configuration = ref(apiClientConfigurationSchema.parse(_configuration));
	const store = _store || createWorkspaceStore({
		proxyUrl: configuration.value.proxyUrl,
		theme: configuration.value.theme,
		showSidebar: configuration.value.showSidebar ?? true,
		hideClientButton: configuration.value.hideClientButton ?? false,
		_integration: configuration.value._integration,
		useLocalStorage: persistData
	});
	const activeEntities = createActiveEntitiesStore({
		...store,
		router
	});
	const sidebarState = createSidebarState({ layout });
	const pluginManager = createPluginManager({ plugins: configuration.value.plugins ?? [] });
	const hasLocalStorage = () => {
		try {
			return typeof window !== "undefined" && window.localStorage !== void 0;
		} catch {
			return false;
		}
	};
	if (hasLocalStorage() && localStorage.getItem(LS_KEYS.WORKSPACE) && !isReadOnly) try {
		const size = {};
		let _lsTotal = 0;
		let _xLen = 0;
		let _key = "";
		for (_key in localStorage) {
			if (!Object.hasOwn(localStorage, _key)) continue;
			_xLen = (localStorage[_key].length + _key.length) * 2;
			_lsTotal += _xLen;
			size[_key] = (_xLen / 1024).toFixed(2) + " KB";
		}
		size["Total"] = (_lsTotal / 1024).toFixed(2) + " KB";
		console.table(size);
		loadAllResources(store);
	} catch (error) {
		console.warn("Failed to load from localStorage:", error);
	}
	else if (!isReadOnly && !configuration.value.url && !configuration.value.content) {
		store.workspaceMutators.add({
			uid: "default",
			name: "Workspace",
			proxyUrl: configuration.value.proxyUrl
		});
		if (hasLocalStorage()) try {
			localStorage.setItem(DATA_VERSION_LS_LEY, DATA_VERSION);
		} catch (error) {
			console.warn("Failed to set localStorage version:", error);
		}
	} else {
		const workspace = workspaceSchema.parse({
			uid: "default",
			name: "Workspace",
			proxyUrl: configuration.value.proxyUrl
		});
		store.workspaceMutators.rawAdd(workspace);
	}
	const app = createApp(appComponent);
	app.use(router);
	app.provide(WORKSPACE_SYMBOL, store);
	app.provide(LAYOUT_SYMBOL, layout);
	app.provide(ACTIVE_ENTITIES_SYMBOL, activeEntities);
	app.provide(SIDEBAR_SYMBOL, sidebarState);
	app.provide(CLIENT_CONFIGURATION_SYMBOL, configuration);
	app.provide(PLUGIN_MANAGER_SYMBOL, pluginManager);
	app.config.idPrefix = "scalar-client";
	const { collectionMutators, importSpecFile, importSpecFromUrl, modalState, requests, securitySchemes, securitySchemeMutators, servers, workspaceMutators, requestExampleMutators } = store;
	const { activeCollection, activeWorkspace } = activeEntities;
	const mount = (mountingEl = el) => {
		if (!mountingEl) {
			console.error("[@scalar/api-client-modal] Could not create the API client.", "Invalid HTML element provided.", "Read more: https://github.com/scalar/scalar/tree/main/packages/api-client");
			return;
		}
		app.mount(mountingEl);
	};
	if (mountOnInitialize) mount();
	/** Route to the specified method and path */
	const route = (payload) => {
		const resolvedRequestUid = getRequestUidByPathMethod(requests, payload);
		if (resolvedRequestUid) router.push({
			name: "request",
			query: payload?._source ? { source: payload._source } : {},
			params: {
				workspace: "default",
				request: resolvedRequestUid
			}
		});
		else console.warn("[@scalar/api-client] Could not find request for path and method", payload);
	};
	/** Reset the client store */
	const resetStore = () => {
		store.collectionMutators.reset();
		store.requestMutators.reset();
		store.requestExampleMutators.reset();
		store.securitySchemeMutators.reset();
		store.serverMutators.reset();
		store.tagMutators.reset();
		workspaceMutators.edit(activeWorkspace.value?.uid, "collections", []);
	};
	return {
		app,
		resetStore,
		updateConfig: async (_newConfig) => {
			const newConfig = apiClientConfigurationSchema.parse(_newConfig);
			if (newConfig.url || newConfig.content || newConfig.servers || newConfig.authentication || newConfig.slug || newConfig.title || newConfig.baseServerURL || newConfig.proxyUrl || newConfig.showSidebar) {
				resetStore();
				/** Add any extra properties to the config */
				const config = {
					...newConfig,
					useCollectionSecurity: isReadOnly
				};
				configuration.value = config;
				if (newConfig.url) await importSpecFromUrl(newConfig.url, activeWorkspace.value?.uid ?? "default", config);
				else if (newConfig.content) await importSpecFile(newConfig.content, activeWorkspace.value?.uid ?? "default", config);
				else console.error("[@scalar/api-client-modal] Could not create the API client.", "Please provide an OpenAPI document: { url: \"…\" }", "Read more: https://github.com/scalar/scalar/tree/main/packages/api-client");
			}
		},
		updateServer: (serverUrl) => {
			const server = Object.values(servers).find((s) => s.url === serverUrl);
			if (server && activeCollection.value) collectionMutators.edit(activeCollection.value?.uid, "selectedServerUid", server.uid);
		},
		onUpdateServer: (callback) => {
			watch(() => activeCollection.value?.selectedServerUid, (uid) => {
				const server = Object.values(servers).find((s) => s.uid === uid);
				if (server?.url) callback(server.url);
			});
		},
		updateAuth: ({ nameKey, propertyKey, value }) => {
			const scheme = Object.values(securitySchemes).find((s) => s.nameKey === nameKey);
			if (scheme) securitySchemeMutators.edit(scheme.uid, propertyKey, value);
		},
		route,
		open: (payload) => {
			const { method, path, requestUid } = payload ?? {};
			if (method && path || requestUid) route(payload);
			modalState.open = true;
		},
		mount,
		modalState,
		store,
		updateExample: (exampleKey, operationId) => {
			if (!exampleKey || !operationId) return;
			const request = Object.values(requests).find(({ operationId: reqOperationId, path }) => reqOperationId === operationId || path === operationId);
			if (!request) return;
			const contentType = Object.keys(request.requestBody?.content || {})[0] || "";
			const example = request.requestBody?.content?.[contentType]?.examples?.[exampleKey];
			if (!example) return;
			requestExampleMutators.edit(request.examples[0], "body.raw.value", prettyPrintJson(example.value));
		}
	};
};
//#endregion
export { createApiClient };

//# sourceMappingURL=create-client.js.map