import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

import { settingsService } from '@/services/settingsService'

const SETTINGS_ID = settingsService.SETTINGS_ID
const DEFAULT_SETTINGS = settingsService.DEFAULT_SETTINGS

export const useSettingsStore = defineStore('settings', () => {
  const state = ref({ ...DEFAULT_SETTINGS })
  const isReady = ref(false)

  async function ensureLoaded() {
    if (isReady.value) return
    const stored = await settingsService.getSettings()
    state.value = { ...DEFAULT_SETTINGS, ...stored, id: SETTINGS_ID }
    isReady.value = true
  }

  async function updateSettings(patch) {
    await ensureLoaded()
    const updated = await settingsService.updateSettings(patch)
    state.value = { ...DEFAULT_SETTINGS, ...updated, id: SETTINGS_ID }
  }

  const searchShortcut = computed(() => state.value.searchShortcut)
  const theme = computed(() => state.value.theme)
  const defaultView = computed(() => state.value.defaultView)
  const libraryView = computed(() => state.value.libraryView || 'tag')

  return {
    state,
    isReady,
    ensureLoaded,
    updateSettings,
    searchShortcut,
    theme,
    defaultView,
    libraryView,
  }
})

