import {atomsStore, PermissionToLoadPresetsAtom} from "../../atoms";

export const updatePreference = async <Value>(id: string, value: Value): Promise<{name: string, value: Value}> => {
    const response = await fetch((window as any).CouponsPlus.urls.rest.preferences, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': (window as any).CouponsPlus.security.nonces.rest
        },
        body: JSON.stringify({
            key: id,
            value: value
        })
    });

    if (!response.ok) {
        throw new Error('Failed to update preference');
    }

    const data = await response.json();

    // Update the corresponding atom based on the preference id
    if (id === 'permissions.connect') {
        atomsStore.set(PermissionToLoadPresetsAtom, value as boolean);
    }

    return {
        name: data.name,
        value: data.value
    };
}