import { get as get$1, set as set$1 } from "../memory/index.js";
import { getEnv } from "../../env.js";
import { PackageCacheStats } from "../../stats.js";
import { cleanup as cleanup$1, get as get$2, init as init$1, set as set$2 } from "./file.js";
import { getCombinedKey } from "./key.js";
import { end, get as get$3, init as init$2, set as set$3 } from "./redis.js";
import { SqlitePackageCache } from "./sqlite.js";
import { getTtlOverride } from "./ttl.js";

//#region lib/util/cache/package/index.ts
let cacheProxy;
let cacheType;
/* v8 ignore next -- not important */
function getCacheType() {
	return cacheType;
}
async function get(namespace, key) {
	if (!cacheProxy) return;
	const combinedKey = getCombinedKey(namespace, key);
	let p = get$1(combinedKey);
	if (!p) {
		p = PackageCacheStats.wrapGet(() => cacheProxy.get(namespace, key));
		set$1(combinedKey, p);
	}
	return await p;
}
/**
* Set cache value with user-defined TTL overrides.
*/
async function set(namespace, key, value, hardTtlMinutes) {
	await setWithRawTtl(namespace, key, value, getTtlOverride(namespace) ?? hardTtlMinutes);
}
/**
* Set cache value ignoring user-defined TTL overrides.
* This MUST NOT be used outside of cache implementation
*/
async function setWithRawTtl(namespace, key, value, hardTtlMinutes) {
	if (!cacheProxy) return;
	await PackageCacheStats.wrapSet(() => cacheProxy.set(namespace, key, value, hardTtlMinutes));
	const combinedKey = getCombinedKey(namespace, key);
	const p = Promise.resolve(value);
	set$1(combinedKey, p);
}
async function init(config) {
	cacheType = void 0;
	if (config.redisUrl) {
		await init$2(config.redisUrl, config.redisPrefix);
		cacheProxy = {
			get: get$3,
			set: set$3
		};
		cacheType = "redis";
		return;
	}
	if (getEnv().RENOVATE_X_SQLITE_PACKAGE_CACHE) {
		cacheProxy = await SqlitePackageCache.init(config.cacheDir);
		cacheType = "sqlite";
		return;
	}
	// v8 ignore else -- TODO: add test #40625
	if (config.cacheDir) {
		init$1(config.cacheDir);
		cacheProxy = {
			get: get$2,
			set: set$2,
			cleanup: cleanup$1
		};
		cacheType = "file";
		return;
	}
}
async function cleanup(config) {
	cacheType = void 0;
	if (config?.redisUrl) await end();
	if (cacheProxy?.cleanup) await cacheProxy.cleanup();
}

//#endregion
export { cleanup, get, getCacheType, init, set, setWithRawTtl };
//# sourceMappingURL=index.js.map