import type Redis from "ioredis";
import { getKeydbClient } from "~/utils/keydb";

export const SCHEDA_ANNUNCIO_CACHE_PREFIX = "scheda-annuncio-";
export const CONDIZIONI_CACHE_PREFIX = "condizioni-";
export const invalidateCache = async (cacheKey: string) => {
	const keybd = getKeydbClient();
	if (keybd) {
		await keybd.del(cacheKey);
	}
};

async function deleteByPrefix(redis: Redis, prefix: string) {
	// Create a stream to find keys matching the pattern
	const stream = redis.scanStream({
		match: `${prefix}*`,
		count: 100, // Process 100 keys per iteration
	});

	stream.on("data", async (keys: string[]) => {
		if (keys.length > 0) {
			// Create a pipeline to delete keys in a single network round-trip
			const pipeline = redis.pipeline();

			// Use UNLINK instead of DEL for better performance on large keys
			keys.forEach((key) => pipeline.unlink(key));

			await pipeline.exec();
			console.log(`Deleted ${keys.length} keys`);
		}
	});

	stream.on("error", (err) => {
		console.error(
			`Error scanning/unlinking keys with prefix ${prefix}: ${err.message}`,
		);
	});
}

export const invalidateAllCaches = async () => {
	const keybd = getKeydbClient();
	if (keybd) {
		await deleteByPrefix(keybd, SCHEDA_ANNUNCIO_CACHE_PREFIX);
		await deleteByPrefix(keybd, CONDIZIONI_CACHE_PREFIX);
	}
};

export const getCacheStats = async () => {
	const keybd = getKeydbClient();
	if (keybd) {
		const schedaKeys = await keybd.keys(`${SCHEDA_ANNUNCIO_CACHE_PREFIX}*`);
		const condizioniKeys = await keybd.keys(`${CONDIZIONI_CACHE_PREFIX}*`);
		return {
			success: true,
			schedaCount: schedaKeys.length,
			condizioniCount: condizioniKeys.length,
		};
	}
	return {
		success: false,
		schedaCount: 0,
		condizioniCount: 0,
	};
};
