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

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)

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

  // Actions
  async function fetchUploadLimit() {
    try {
      loading.value = true
      error.value = null
      uploadLimit.value = await settingsService.getUploadLimit()
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to fetch upload limit'
      console.error('Error fetching upload limit:', err)
    } finally {
      loading.value = false
    }
  }

  async function updateUploadLimit(limitMB: number) {
    try {
      loading.value = true
      error.value = null
      uploadLimit.value = await settingsService.updateUploadLimit({ upload_limit_mb: limitMB })
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to update upload limit'
      console.error('Error updating upload limit:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  async function fetchAllSettings() {
    try {
      loading.value = true
      error.value = null
      allSettings.value = await settingsService.getAllSettings()
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to fetch settings'
      console.error('Error fetching settings:', err)
    } finally {
      loading.value = false
    }
  }

  async function createSetting(setting: { setting_key: string; setting_value: string; description?: string }) {
    try {
      loading.value = true
      error.value = null
      const newSetting = await settingsService.createSetting(setting)
      allSettings.value.push(newSetting)
      return newSetting
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to create setting'
      console.error('Error creating setting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  async function updateSetting(settingKey: string, update: { setting_value: string; description?: string }) {
    try {
      loading.value = true
      error.value = null
      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
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to update setting'
      console.error('Error updating setting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  async function deleteSetting(settingKey: string) {
    try {
      loading.value = true
      error.value = null
      await settingsService.deleteSetting(settingKey)
      allSettings.value = allSettings.value.filter(s => s.setting_key !== settingKey)
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to delete setting'
      console.error('Error deleting setting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  function clearError() {
    error.value = null
  }

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