import { appPreferences } from '@axium/core';
import Cache from './cache.js';
import { fetchAPI } from './requests.js';
const cache = new Cache(async (userId, appId) => {
    const schema = appPreferences.get(appId);
    if (!schema)
        throw new Error(`Missing schema for "${appId}"`);
    const result = await fetchAPI('GET', 'users/:id/preferences/:appId', {}, userId, appId);
    return schema.parse(result);
});
export async function get(userId, appId) {
    return (await cache.get(userId, appId));
}
export async function set(userId, appId, preferences) {
    const schema = appPreferences.get(appId);
    if (!schema)
        throw new Error(`Missing schema for "${appId}"`);
    const result = await fetchAPI('POST', 'users/:id/preferences/:appId', preferences, userId, appId);
    cache.set(userId, appId, result);
    return schema.parse(result);
}
export async function clear(userId, appId) {
    const schema = appPreferences.get(appId);
    if (!schema)
        throw new Error(`Missing schema for "${appId}"`);
    const result = await fetchAPI('DELETE', 'users/:id/preferences/:appId', {}, userId, appId);
    cache.invalidate(userId, appId);
    return schema.parse(result);
}
export async function appPref(userId, appId, key) {
    const pref = await get(userId, appId);
    return pref[key];
}
