const cache = new Map<string, { timestamp: number; data: any }>();
const DEFAULT_TTL = 1000 * 60 * 15; // 15 minutes default TTL

/**
 * Caches the result of a promise-returning function.
 * @param key Unique key for the cache entry.
 * @param fetcher Function that returns a promise with the data to cache.
 * @param ttl Time to live in milliseconds. Defaults to 15 minutes.
 */
export async function withCache<T>(key: string, fetcher: () => Promise<T>, ttl = DEFAULT_TTL): Promise<T> {
    const now = Date.now();
    const entry = cache.get(key);

    if (entry && (now - entry.timestamp < ttl)) {
        return entry.data as T;
    }

    try {
        const data = await fetcher();
        cache.set(key, { timestamp: now, data });
        return data;
    } catch (error) {
        console.error(`Error fetching data for key ${key}:`, error);
        // If fetch fails but we have stale data, return it? 
        // For now, let's bubble the error up so the page handles it (e.g. 404), 
        // or maybe just re-throw.
        throw error;
    }
}

/**
 * Manually clears a specific cache key.
 */
export function clearCache(key: string) {
    cache.delete(key);
}

/**
 * Clears the entire cache.
 */
export function clearAllCache() {
    cache.clear();
}
