import { rpc } from './request';

// Кеш в памяти (очищается при перезагрузке страницы)
const memoryCache = new Map<string, unknown>();

const getCacheKey = (method: string, params?: unknown): string => {
    if (params === undefined) {
        return `rpc:${method}`;
    }

    return `rpc:${method}:${JSON.stringify(params)}`;
};

const readCache = <T>(key: string): T | null => {
    const cached = memoryCache.get(key);
    if (cached === undefined) {
        return null;
    }
    return cached as T;
};

const writeCache = <T>(key: string, data: T): void => {
    memoryCache.set(key, data);
};

export const rpcCache = {



    // rpc.collection
    collection: async (
        params: Parameters<typeof rpc.collection>[0],
    ): Promise<Awaited<ReturnType<typeof rpc.collection>>> => {
        const key = getCacheKey('collection', params);
        const cached = readCache<Awaited<ReturnType<typeof rpc.collection>>>(key);
        if (cached) {
            return cached;
        }

        const result = await rpc.collection(params);
        writeCache(key, result);
        return result;
    },


    // rpc.init
    init: async (): Promise<Awaited<ReturnType<typeof rpc.init>>> => {
        const key = getCacheKey('init');
        const cached = readCache<Awaited<ReturnType<typeof rpc.init>>>(key);
        if (cached) {
            return cached;
        }

        const result = await rpc.init();
        writeCache(key, result);
        return result;
    },

    // rpc.menu
    menu: async (): Promise<Awaited<ReturnType<typeof rpc.menu>>> => {
        const key = getCacheKey('menu');
        const cached = readCache<Awaited<ReturnType<typeof rpc.menu>>>(key);
        if (cached) {
            return cached;
        }

        const result = await rpc.menu();
        writeCache(key, result);
        return result;
    },
};


