import { getConfig } from "./api.js";
//#region extensions/weixin/src/api/config-cache.ts
const CONFIG_CACHE_TTL_MS = 1440 * 60 * 1e3;
const CONFIG_CACHE_INITIAL_RETRY_MS = 2e3;
const CONFIG_CACHE_MAX_RETRY_MS = 3600 * 1e3;
/**
* Per-user getConfig cache with periodic random refresh (within 24h) and
* exponential-backoff retry (up to 1h) on failure.
*/
var WeixinConfigManager = class {
	cache = /* @__PURE__ */ new Map();
	constructor(apiOpts, log) {
		this.apiOpts = apiOpts;
		this.log = log;
	}
	async getForUser(userId, contextToken) {
		const now = Date.now();
		const entry = this.cache.get(userId);
		if (!entry || now >= entry.nextFetchAt) {
			let fetchOk = false;
			try {
				const resp = await getConfig({
					baseUrl: this.apiOpts.baseUrl,
					token: this.apiOpts.token,
					routeTag: this.apiOpts.routeTag,
					ilinkUserId: userId,
					contextToken
				});
				if (resp.ret === 0) {
					this.cache.set(userId, {
						config: { typingTicket: resp.typing_ticket ?? "" },
						everSucceeded: true,
						nextFetchAt: now + Math.random() * CONFIG_CACHE_TTL_MS,
						retryDelayMs: CONFIG_CACHE_INITIAL_RETRY_MS
					});
					this.log(`[weixin] config ${entry?.everSucceeded ? "refreshed" : "cached"} for ${userId}`);
					fetchOk = true;
				}
			} catch (err) {
				this.log(`[weixin] getConfig failed for ${userId} (ignored): ${String(err)}`);
			}
			if (!fetchOk) {
				const prevDelay = entry?.retryDelayMs ?? CONFIG_CACHE_INITIAL_RETRY_MS;
				const nextDelay = Math.min(prevDelay * 2, CONFIG_CACHE_MAX_RETRY_MS);
				if (entry) {
					entry.nextFetchAt = now + nextDelay;
					entry.retryDelayMs = nextDelay;
				} else this.cache.set(userId, {
					config: { typingTicket: "" },
					everSucceeded: false,
					nextFetchAt: now + CONFIG_CACHE_INITIAL_RETRY_MS,
					retryDelayMs: CONFIG_CACHE_INITIAL_RETRY_MS
				});
			}
		}
		return this.cache.get(userId)?.config ?? { typingTicket: "" };
	}
};
//#endregion
export { WeixinConfigManager };

//# sourceMappingURL=config-cache.js.map