import { getLogger } from "./logger.js";

//#region src/utils/wait-until.ts
const logger = getLogger("wait-until");
let _importPromise;
/**
* Lazy-load and cache Vercel's `waitUntil` function.
*
* - On Vercel (`process.env.VERCEL` set): dynamically imports `@vercel/functions`
*   and returns `waitUntil`, which extends the serverless function lifetime
*   past the HTTP response so background work can complete.
* - Outside Vercel: returns `undefined`. Callers should let the promise
*   execute naturally via the Node.js event loop (fire-and-forget with
*   error handling).
* - Import failure: logs a warning and returns `undefined` (graceful degradation).
* - Result is cached after first call (lazy singleton). Concurrent callers
*   share the same import promise to avoid duplicate imports.
*/
async function getWaitUntil() {
	if (_importPromise) return _importPromise;
	_importPromise = (async () => {
		if (!process.env.VERCEL) return void 0;
		try {
			return (await import("@vercel/functions")).waitUntil;
		} catch (e) {
			logger.warn({ error: e }, "Failed to import @vercel/functions, waitUntil unavailable");
			return;
		}
	})();
	return _importPromise;
}
/**
* Reset internal cache. Exposed only for testing.
*/
function _resetWaitUntilCache() {
	_importPromise = void 0;
}

//#endregion
export { _resetWaitUntilCache, getWaitUntil };