import { isUrl } from "../../../libs/isUrl.js";
import { reactive } from "vue";
import { fetchWithProxyFallback } from "@scalar/oas-utils/helpers";
import { redirectToProxy } from "@scalar/helpers/url/redirect-to-proxy";
import { resolve } from "@scalar/import";
//#region src/components/ImportCollection/hooks/useUrlPrefetcher.ts
/**
* Vue composable for URL prefetching
*/
function useUrlPrefetcher() {
	const prefetchResult = reactive({
		state: "idle",
		content: null,
		url: null,
		input: null,
		error: null
	});
	function resetPrefetchResult() {
		Object.assign(prefetchResult, {
			state: "idle",
			content: null,
			url: null,
			input: null,
			error: null
		});
	}
	async function prefetchUrl(input, proxyUrl) {
		if (!input) return {
			state: "idle",
			content: null,
			url: null,
			input,
			error: null
		};
		try {
			const urlOrDocument = await resolve(input, { fetch: (url) => {
				return fetch(proxyUrl ? redirectToProxy(proxyUrl, url) : url, { cache: "no-cache" });
			} });
			if (typeof urlOrDocument === "object" && urlOrDocument !== null) return {
				state: "idle",
				content: JSON.stringify(urlOrDocument, null, 2),
				url: null,
				error: null
			};
			if (urlOrDocument === void 0) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: `Could not find an OpenAPI document in ${input}`
			};
			if (!isUrl(urlOrDocument)) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: "Oops, we got invalid content for the given URL."
			};
			const url = urlOrDocument;
			const result = await fetchWithProxyFallback(url, {
				proxyUrl,
				cache: "no-cache"
			});
			if (!result.ok) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: `Couldn't fetch ${url}, got error ${[result.status, result.statusText].join(" ").trim()}.`
			};
			return {
				state: "idle",
				content: await result.text(),
				url,
				error: null
			};
		} catch (error) {
			console.error("[prefetchDocument]", error);
			return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: error.message
			};
		}
	}
	async function prefetchUrlAndUpdateState(input, proxyUrl) {
		Object.assign(prefetchResult, {
			state: "loading",
			content: null,
			url: null,
			input,
			error: null
		});
		const result = await prefetchUrl(input, proxyUrl);
		Object.assign(prefetchResult, result);
		return result;
	}
	return {
		prefetchResult,
		prefetchUrl: prefetchUrlAndUpdateState,
		resetPrefetchResult
	};
}
//#endregion
export { useUrlPrefetcher };

//# sourceMappingURL=useUrlPrefetcher.js.map