import { defineStore } from 'pinia'
import { ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { handleInvokeError } from '../utils/errorHandler'

export const useSettingsStore = defineStore('settings', () => {
  const settings = ref<Record<string, string>>({})
  const loading = ref(false)

  async function fetchSettings() {
    loading.value = true
    try {
      settings.value = await invoke<Record<string, string>>('get_settings')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch settings', () => fetchSettings())
    } finally {
      loading.value = false
    }
  }

  async function updateSetting(key: string, value: string): Promise<boolean> {
    try {
      await invoke('update_settings', { key, value })
      settings.value[key] = value
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to save setting')
      return false
    }
  }

  return {
    settings,
    loading,
    fetchSettings,
    updateSetting
  }
})
