import { getOAuthAPI } from "./getIntlayerAPI/oAuth.mjs";
import { getIntlayerAPI } from "./getIntlayerAPI/index.mjs";

//#region ../@intlayer/chokidar/dist/esm/api/dist/esm/proxy.mjs
const ONE_MINUTE_MS = 6e4;
/**
* Returns the expiration timestamp in ms from an OAuth token-like object.
*/
const getExpiryTimestamp = (token) => {
	if (!token) return void 0;
	const dateLike = token.accessTokenExpiresAt ?? token.expiresAt;
	if (dateLike) {
		const ts = typeof dateLike === "string" ? Date.parse(dateLike) : dateLike.getTime?.();
		if (typeof ts === "number" && Number.isFinite(ts)) return ts;
	}
	const seconds = token.expires_in ?? token.expiresIn;
	if (typeof seconds === "number" && Number.isFinite(seconds)) return Date.now() + seconds * 1e3;
};
let currentAccessToken;
let currentExpiryTs;
let pendingRefresh;
/**
* Build an auto-auth proxy around getIntlayerAPI that:
* - Fetches an OAuth2 token when needed
* - Injects Authorization header for each request
* - Refreshes token proactively when near expiry
*
* The returned API matches the shape of getIntlayerAPI.
*/
const getIntlayerAPIProxy = (_baseAuthOptions = {}, intlayerConfig) => {
	const authOptionsRef = { ..._baseAuthOptions };
	const hasCMSAuth = intlayerConfig?.editor?.clientId && intlayerConfig?.editor?.clientSecret;
	const baseApi = getIntlayerAPI(authOptionsRef, intlayerConfig);
	const needsRefresh = () => {
		if (!currentAccessToken) return true;
		if (!currentExpiryTs) return false;
		return Date.now() + ONE_MINUTE_MS >= currentExpiryTs;
	};
	const refreshToken = async () => {
		const doRefresh = async () => {
			const tokenData = (await getOAuthAPI(intlayerConfig).getOAuth2AccessToken())?.data;
			currentAccessToken = tokenData?.accessToken;
			currentExpiryTs = getExpiryTimestamp(tokenData);
		};
		if (!pendingRefresh) pendingRefresh = doRefresh().finally(() => {
			pendingRefresh = void 0;
		});
		await pendingRefresh;
	};
	const ensureValidToken = async () => {
		if (needsRefresh()) await refreshToken();
	};
	const applyAuthHeaderToRef = () => {
		if (!currentAccessToken) return;
		authOptionsRef.headers = {
			...authOptionsRef.headers ?? {},
			Authorization: `Bearer ${currentAccessToken}`
		};
	};
	const wrapSection = (section, skipAuth = !hasCMSAuth) => {
		return new Proxy(section, { get(target, prop, receiver) {
			const value = Reflect.get(target, prop, receiver);
			if (typeof value === "function") return async (...args) => {
				if (!skipAuth) {
					await ensureValidToken();
					applyAuthHeaderToRef();
				}
				try {
					return await value.apply(target, args);
				} catch (err) {
					if (!skipAuth) {
						await refreshToken();
						applyAuthHeaderToRef();
						return await value.apply(target, args);
					}
					throw err;
				}
			};
			return value;
		} });
	};
	return {
		organization: wrapSection(baseApi.organization),
		project: wrapSection(baseApi.project),
		user: wrapSection(baseApi.user),
		oAuth: wrapSection(baseApi.oAuth, true),
		dictionary: wrapSection(baseApi.dictionary),
		stripe: wrapSection(baseApi.stripe),
		ai: wrapSection(baseApi.ai),
		tag: wrapSection(baseApi.tag),
		search: wrapSection(baseApi.search),
		editor: wrapSection(baseApi.editor),
		newsletter: wrapSection(baseApi.newsletter),
		audit: wrapSection(baseApi.audit)
	};
};

//#endregion
export { getIntlayerAPIProxy };
//# sourceMappingURL=proxy.mjs.map