import { computed, ref } from 'vue'
import { authState, isLoggedIn } from './auth'
import {
  fetchWishlist as apiFetchWishlist,
  addToWishlist as apiAddToWishlist,
  removeFromWishlist as apiRemoveFromWishlist
} from './api'

const wishlistIds = ref([])
const wishlistSet = computed(() => new Set(wishlistIds.value))
const wishlistCount = computed(() => wishlistIds.value.length)

const loadWishlist = async () => {
  if (!isLoggedIn()) {
    wishlistIds.value = []
    return
  }
  try {
    wishlistIds.value = await apiFetchWishlist(authState.token)
  } catch {
    wishlistIds.value = []
  }
}

const isInWishlist = (productId) => wishlistSet.value.has(productId)

const addToWishlist = async (productId) => {
  if (!isLoggedIn()) return
  try {
    wishlistIds.value = await apiAddToWishlist(authState.token, productId)
  } catch {
    // 忽略错误
  }
}

const removeFromWishlist = async (productId) => {
  if (!isLoggedIn()) return
  try {
    wishlistIds.value = await apiRemoveFromWishlist(authState.token, productId)
  } catch {
    // 忽略错误
  }
}

const toggleWishlist = async (productId) => {
  if (isInWishlist(productId)) {
    await removeFromWishlist(productId)
  } else {
    await addToWishlist(productId)
  }
}

const getWishlistProducts = (allProducts) => {
  const idSet = wishlistSet.value
  return allProducts.filter((p) => idSet.has(p.id))
}

export {
  wishlistCount,
  isInWishlist,
  addToWishlist,
  removeFromWishlist,
  toggleWishlist,
  getWishlistProducts,
  loadWishlist
}
