import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { isTauri, getTauriStore, setServerUrl } from '@/lib/tauri'

export const useServerConfig = defineStore('server-config', () => {
  const serverUrl = ref('')
  const isConfigured = computed(() => !!serverUrl.value)
  const loading = ref(false)
  const error = ref('')
  const recentUrls = ref<string[]>([])

  /** Load saved config from Tauri store */
  async function loadConfig() {
    if (!isTauri) return

    try {
      const store = await getTauriStore()
      const saved = await store.get<string>('serverUrl')
      if (saved) {
        serverUrl.value = saved
        setServerUrl(saved)
      }
      const savedRecent = await store.get<string[]>('recentUrls')
      if (savedRecent) {
        recentUrls.value = savedRecent
      }
    } catch (e) {
      console.warn('[ServerConfig] Failed to load config:', e)
    }
  }

  /** Test connection to a server URL */
  async function testConnection(url: string): Promise<boolean> {
    try {
      const normalizedUrl = url.replace(/\/+$/, '')
      const { fetch: tauriFetch } = await import('@tauri-apps/plugin-http')
      const res = await tauriFetch(`${normalizedUrl}/api/health`, {
        method: 'GET',
      })
      return res.ok
    } catch {
      return false
    }
  }

  /** Set and persist the server URL (validates connectivity first) */
  async function setServer(url: string): Promise<boolean> {
    loading.value = true
    error.value = ''

    try {
      const normalizedUrl = url.replace(/\/+$/, '')
      const ok = await testConnection(normalizedUrl)
      if (!ok) {
        error.value = 'Could not connect to server'
        return false
      }

      serverUrl.value = normalizedUrl
      setServerUrl(normalizedUrl)

      // Persist to Tauri store
      const store = await getTauriStore()
      await store.set('serverUrl', normalizedUrl)

      // Update recent URLs
      const filtered = recentUrls.value.filter(u => u !== normalizedUrl)
      recentUrls.value = [normalizedUrl, ...filtered].slice(0, 5)
      await store.set('recentUrls', recentUrls.value)
      await store.save()

      return true
    } catch (e: any) {
      error.value = e.message || 'Unknown error'
      return false
    } finally {
      loading.value = false
    }
  }

  /** Clear the saved configuration */
  async function clearConfig() {
    serverUrl.value = ''
    setServerUrl('')
    error.value = ''

    if (isTauri) {
      try {
        const store = await getTauriStore()
        await store.delete('serverUrl')
        await store.save()
      } catch (e) {
        console.warn('[ServerConfig] Failed to clear config:', e)
      }
    }
  }

  return {
    serverUrl,
    isConfigured,
    loading,
    error,
    recentUrls,
    loadConfig,
    testConnection,
    setServer,
    clearConfig,
  }
})
