export const useCartStore = defineStore('cart', {
    state: () => {
        return {
            items: [],
            loading: false
        }
    },
    getters: {
        count: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0) || 0,
        find: (state) => (id) => state.items.find((item) => item.product?.id == id)
    },
    actions: {
        async get() {
            const { status, data } = await useFetch('/api/users/current/cart', {
                headers: { Authorization: useCookie('token') }
            })

            if (status.value == 'success') {
                this.items = data.value.cart
            }
        },
        async clear() {
            const { status } = await useFetch('/api/users/cart', {
                headers: { Authorization: useCookie('token') }, method: 'delete', body: {}
            })

            if (status.value == 'success') {
                this.items = []
            }
        },
        async update(product, quantity = 0) {
            this.loading = true
            const cart = { product }
            if (quantity > 0) {
                //update
                let item = this.find(product)
                if (item) item.quantity = quantity

                cart.quantity = quantity
                const { status, data } = await useFetch('/api/users/cart', {
                    headers: { Authorization: useCookie('token') }, method: 'put', body: { cart }
                })
                if (status.value == 'success') {
                    const temp = { product: data.value, quantity }
                    if (item) item = temp
                    else this.items.push(temp)
                }
            } else {
                //remove
                const { status } = await useFetch('/api/users/cart', {
                    headers: { Authorization: useCookie('token') }, method: 'patch', body: { cart }
                })
                if (status.value == 'success') {
                    this.items = this.items.filter((item) => item.product.id != product)
                }
            }
            this.loading = false
        }
    }
})
