import { ref } from 'vue'
import { apiFetch } from '@/lib/tauri'

// Uses relative URLs - works with Vite proxy in dev and Traefik in production
const API_BASE = '/api/database'

export function useQueryExecutor() {
  const queryText = ref('')
  const queryResult = ref<any[] | null>(null)
  const queryError = ref<string | null>(null)
  const queryLoading = ref(false)

  async function executeQuery() {
    if (!queryText.value.trim()) return

    queryLoading.value = true
    queryError.value = null
    queryResult.value = null

    try {
      const res = await apiFetch(`${API_BASE}/query`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: queryText.value })
      })

      const result = await res.json()

      if (!res.ok) {
        queryError.value = result.error || 'Query failed'
      } else {
        queryResult.value = result.rows
      }
    } catch (e: any) {
      queryError.value = e.message
    } finally {
      queryLoading.value = false
    }
  }

  function reset() {
    queryText.value = ''
    queryResult.value = null
    queryError.value = null
  }

  return {
    queryText,
    queryResult,
    queryError,
    queryLoading,
    executeQuery,
    reset
  }
}
