import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { GlobalFilterSettings, DEFAULT_FILTER_SETTINGS } from '@/types/filter.types'

/**
 * 전역 필터 Store
 * Zustand + persist로 localStorage 자동 관리
 */
interface FilterState {
  filters: GlobalFilterSettings
  isLoading: boolean
  updateFilters: (newFilters: Partial<GlobalFilterSettings>) => void
  resetFilters: () => void
  setLoading: (loading: boolean) => void
}

export const useFilterStore = create<FilterState>()(
  persist(
    (set) => ({
      filters: DEFAULT_FILTER_SETTINGS,
      isLoading: false,

      updateFilters: (newFilters: Partial<GlobalFilterSettings>) => {
        set((state) => ({
          filters: {
            ...state.filters,
            ...newFilters,
            updtDt: new Date(),
          },
        }))
      },

      resetFilters: () => {
        set({ filters: DEFAULT_FILTER_SETTINGS })
      },

      setLoading: (loading: boolean) => {
        set({ isLoading: loading })
      },
    }),
    {
      name: 'global-filter-storage',
      partialize: (state) => ({
        filters: state.filters,
      }),
      merge: (persistedState, currentState) => {
        const persisted = persistedState as { filters?: GlobalFilterSettings }

        // localStorage에 저장된 값이 없거나, selectedTraits가 비어있으면 기본값 적용
        if (!persisted?.filters ||
            !persisted.filters.selectedTraits ||
            persisted.filters.selectedTraits.length === 0) {
          return {
            ...currentState,
            filters: DEFAULT_FILTER_SETTINGS,
          }
        }

        return {
          ...currentState,
          filters: persisted.filters,
        }
      },
    }
  )
)
