import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import type { BasketItem } from '@/types/basket'
import { getBasketItemKey } from '@/utils/basketKeys'

const STORAGE_KEY = 'research-basket-items'

/** Omit 分发到联合类型的每个成员，保留鉴别器字段（item_type）和各子类型特有字段 */
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never

function loadStoredItems(): BasketItem[] {
  const raw = localStorage.getItem(STORAGE_KEY)
  if (!raw) return []

  try {
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed : []
  } catch {
    return []
  }
}

export const useBasketStore = defineStore('basket', () => {
  const items = ref<BasketItem[]>(loadStoredItems())
  const drawerVisible = ref(false)

  watch(
    items,
    (value) => {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(value))
    },
    { deep: true },
  )

  const count = computed(() => items.value.length)

  function addItem(item: DistributiveOmit<BasketItem, 'added_at'> & { added_at?: number }): boolean {
    const normalizedItem = {
      ...item,
      added_at: item.added_at ?? Date.now(),
    } as BasketItem

    const itemKey = getBasketItemKey(normalizedItem)
    const exists = items.value.some((existing) => getBasketItemKey(existing) === itemKey)
    if (exists) return false

    items.value.unshift(normalizedItem)
    return true
  }

  function removeItem(item: BasketItem) {
    const itemKey = getBasketItemKey(item)
    items.value = items.value.filter((existing) => getBasketItemKey(existing) !== itemKey)
  }

  function clearAll() {
    items.value = []
  }

  function openDrawer() {
    drawerVisible.value = true
  }

  function closeDrawer() {
    drawerVisible.value = false
  }

  function toggleDrawer(force?: boolean) {
    drawerVisible.value = typeof force === 'boolean' ? force : !drawerVisible.value
  }

  return {
    items,
    count,
    drawerVisible,
    addItem,
    removeItem,
    clearAll,
    openDrawer,
    closeDrawer,
    toggleDrawer,
  }
})