import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { settingsService, type UploadLimitResponse, type GlobalSetting } from '@/services/settings'
import { useAsyncAction } from '@/composables/useAsyncAction'

export const useSettingsStore = defineStore('settings', () => {
  const uploadLimit = ref<UploadLimitResponse | null>(null)
  const allSettings = ref<GlobalSetting[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const { run } = useAsyncAction({ isLoading: loading, error })

  // Computed
  const uploadLimitMB = computed(() => uploadLimit.value?.upload_limit_mb || 1000)
  const uploadLimitBytes = computed(() => uploadLimitMB.value * 1024 * 1024)

  // Actions
  async function fetchUploadLimit() {
    return run(async () => {
      uploadLimit.value = await settingsService.getUploadLimit()
    }, { errorMessage: 'Failed to fetch upload limit', rethrow: false })
  }

  async function updateUploadLimit(limitMB: number) {
    return run(async () => {
      uploadLimit.value = await settingsService.updateUploadLimit({ upload_limit_mb: limitMB })
    }, { errorMessage: 'Failed to update upload limit' })
  }

  async function fetchAllSettings() {
    return run(async () => {
      allSettings.value = await settingsService.getAllSettings()
    }, { errorMessage: 'Failed to fetch settings', rethrow: false })
  }

  async function createSetting(setting: { setting_key: string; setting_value: string; description?: string }) {
    return run(async () => {
      const newSetting = await settingsService.createSetting(setting)
      allSettings.value.push(newSetting)
      return newSetting
    }, { errorMessage: 'Failed to create setting' })
  }

  async function updateSetting(settingKey: string, update: { setting_value: string; description?: string }) {
    return run(async () => {
      const updatedSetting = await settingsService.updateSetting(settingKey, update)
      const index = allSettings.value.findIndex(s => s.setting_key === settingKey)
      if (index !== -1) {
        allSettings.value[index] = updatedSetting
      }
      return updatedSetting
    }, { errorMessage: 'Failed to update setting' })
  }

  async function deleteSetting(settingKey: string) {
    return run(async () => {
      await settingsService.deleteSetting(settingKey)
      allSettings.value = allSettings.value.filter(s => s.setting_key !== settingKey)
    }, { errorMessage: 'Failed to delete setting' })
  }

  function clearError() {
    error.value = null
  }

  return {
    // State
    uploadLimit,
    allSettings,
    loading,
    error,
    
    // Computed
    uploadLimitMB,
    uploadLimitBytes,
    
    // Actions
    fetchUploadLimit,
    updateUploadLimit,
    fetchAllSettings,
    createSetting,
    updateSetting,
    deleteSetting,
    clearError
  }
})