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 { isLoading, cart = null } = get();

        // only fetch if not being fetched yet and no cache
        if (!isLoading && !cart && window?.fetch) {
            set({ isLoading: true });

            // Small delay to ensure preview cookie is set before fetching the cart
            // This is a workaround for the preview mode where the cookie might not be set immediately
            // This delay is necessary to ensure that the preview cookie is set before fetching the cart
            await new Promise(resolve => { setTimeout(resolve, 100); });

            const endpoint = getCartApiEndpoint(locale);
            const raw = await fetch(endpoint);
            let cartResponse = {};
            try {
                cartResponse = await raw.json();
            } catch (error) {
                console.log('Cart anonymous/failed', error);
            }

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