import { writable } from 'svelte/store'
import { stockApi } from '$lib/api/stock'
import type { WatchlistItem } from '$lib/api/types'

// 관심종목 스토어 (서버 동기화)
function createWatchlistStore() {
  const { subscribe, set, update } = writable<WatchlistItem[]>([])

  return {
    subscribe,

    // 서버에서 목록 로딩
    async load() {
      try {
        const list = await stockApi.getWatchlist()
        set(list ?? [])
      } catch {
        set([])
      }
    },

    // 관심종목 추가
    async add(code: string, name: string) {
      await stockApi.addWatchlist(code, name)
      update((list) => {
        if (list.some((i) => i.code === code)) return list
        return [...list, { code, name }]
      })
    },

    // 관심종목 삭제
    async remove(code: string) {
      await stockApi.removeWatchlist(code)
      update((list) => list.filter((i) => i.code !== code))
    },

    // 포함 여부 확인 (동기)
    has(list: WatchlistItem[], code: string) {
      return list.some((i) => i.code === code)
    },
  }
}

export const watchlist = createWatchlistStore()
