import { ref, computed } from "vue";

export function useCart() {
    const cart = ref({});

    const updateQty = (productId, delta, productPrice) => {
        const currentQty = cart.value[productId]?.qty || 0;
        const newQty = currentQty + delta;

        if (newQty <= 0) {
            delete cart.value[productId];
        } else {
            cart.value[productId] = {
                qty: newQty,
                price: productPrice,
            };
        }
    };

    const getQty = (productId) => {
        return cart.value[productId]?.qty || 0;
    };

    const totalItems = computed(() => {
        return Object.values(cart.value).reduce(
            (sum, item) => sum + item.qty,
            0,
        );
    });

    const totalAmount = computed(() => {
        return Object.values(cart.value).reduce(
            (sum, item) => sum + item.price * item.qty,
            0,
        );
    });

    const cartItems = computed(() => {
        return Object.entries(cart.value).map(([productId, item]) => ({
            product_id: parseInt(productId),
            qty: item.qty,
        }));
    });

    const clearCart = () => {
        cart.value = {};
    };

    return {
        cart,
        updateQty,
        getQty,
        totalItems,
        totalAmount,
        cartItems,
        clearCart,
    };
}
