import create from 'zustand';
import { getCartApiEndpoint } from '../tools/urlTools';

// FIXME: SFB-3815 generalize to a "cached fetch factory"

export const cartPreviewStore = create((set, get) => ({
    cart: null, // {} is an empty cart
    isLoading: false,
    setLoading: isLoading => {
        set({ isLoading });
    },
    clearCart: () => {
        set({ cart: null, isLoading: false });
    },
    fetchCart: async (locale = 'en-US') => {
        const endpoint = getCartApiEndpoint(locale);

        const { isLoading, cart = null } = get();

        // only fetch if not being fetched yet and no cache
        if (!isLoading && !cart && window?.fetch) {
            set({ isLoading: true });
            const raw = await fetch(endpoint);
            const cartResponse = await raw.json();

            set({ cart: cartResponse });
            set({ isLoading: false });
        }
    }
}));
