// In-memory cache client (Redis replacement)
// This lightweight drop-in replaces Redis usage without external dependency

const store = new Map();

function now() {
	return Date.now();
}

function setEx(key, ttlSeconds, value) {
	const expiresAt = now() + ttlSeconds * 1000;
	store.set(key, { value, expiresAt });

	// Schedule deletion
	setTimeout(() => {
		const entry = store.get(key);
		if (entry && entry.expiresAt <= now()) {
			store.delete(key);
		}
	}, ttlSeconds * 1000 + 50);

	return Promise.resolve("OK");
}

async function get(key) {
	const entry = store.get(key);
	if (!entry) return null;
	if (entry.expiresAt <= now()) {
		store.delete(key);
		return null;
	}
	return entry.value;
}

function del(key) {
	store.delete(key);
	return Promise.resolve(1);
}

module.exports = {
	setEx,
	get,
	del,
	// Delete all keys starting with a prefix (namespace invalidation)
	delByPrefix: async (prefix) => {
		for (const key of store.keys()) {
			if (key.startsWith(prefix)) {
				store.delete(key);
			}
		}
		return 1;
	},
};
