import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { cartApi } from '../api'

export const useCartStore = defineStore('cart', () => {
  const items = ref<any[]>([])
  const loading = ref(false)
  const totalAmount = ref(0)
  const totalCount = ref(0)

  async function fetchCart() {
    loading.value = true
    try {
      const res: any = await cartApi.list()
      items.value = res.data || []
    } finally {
      loading.value = false
    }
  }

  async function addItem(productId: number, quantity: number) {
    await cartApi.add({ product_id: productId, quantity })
    await fetchCart()
  }

  async function updateItem(id: number, quantity: number) {
    await cartApi.update(id, { quantity })
    await fetchCart()
  }

  async function removeItem(id: number) {
    await cartApi.delete(id)
    await fetchCart()
  }

  async function removeItems(ids: number[]) {
    await Promise.all(ids.map(id => cartApi.delete(id)))
    await fetchCart()
  }

  function clearCart() {
    items.value = []
    totalAmount.value = 0
    totalCount.value = 0
  }

  function calcTotals() {
    totalAmount.value = items.value.reduce((sum, item) => sum + (item.product?.price || 0) * item.quantity, 0)
    totalCount.value = items.value.reduce((sum, item) => sum + item.quantity, 0)
  }

  watch(items, calcTotals, { deep: true })

  return {
    items,
    loading,
    totalAmount,
    totalCount,
    fetchCart,
    addItem,
    updateItem,
    removeItem,
    removeItems,
    clearCart
  }
})
