import { ref } from 'vue'
import { apiFetch } from '@/lib/tauri'
import type { TableInfo, TableSchema, DbStats } from '@/types/database'

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

export function useDatabaseApi() {
  const tables = ref<TableInfo[]>([])
  const tableSchema = ref<TableSchema[]>([])
  const tableData = ref<any[]>([])
  const dbStats = ref<DbStats | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const totalRecords = ref(0)

  async function fetchTables() {
    loading.value = true
    error.value = null
    try {
      const res = await apiFetch(`${API_BASE}/tables`)
      if (!res.ok) throw new Error('Failed to fetch tables')
      tables.value = await res.json()
    } catch (e: any) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  async function fetchDbStats() {
    try {
      const res = await apiFetch(`${API_BASE}/stats`)
      if (!res.ok) throw new Error('Failed to fetch stats')
      dbStats.value = await res.json()
    } catch (e: any) {
      console.error('Error fetching stats:', e)
    }
  }

  async function fetchTableSchema(tableName: string) {
    try {
      const res = await apiFetch(`${API_BASE}/tables/${tableName}/schema`)
      if (!res.ok) throw new Error('Failed to fetch schema')
      tableSchema.value = await res.json()
    } catch (e: any) {
      console.error('Error fetching schema:', e)
      tableSchema.value = []
    }
  }

  async function fetchTableData(tableName: string, page: number, pageSize: number) {
    loading.value = true
    try {
      const offset = (page - 1) * pageSize
      const res = await apiFetch(`${API_BASE}/tables/${tableName}/data?limit=${pageSize}&offset=${offset}`)
      if (!res.ok) throw new Error('Failed to fetch data')
      const result = await res.json()
      tableData.value = result.rows
      totalRecords.value = result.total
    } catch (e: any) {
      console.error('Error fetching data:', e)
      tableData.value = []
    } finally {
      loading.value = false
    }
  }

  return {
    tables,
    tableSchema,
    tableData,
    dbStats,
    loading,
    error,
    totalRecords,
    fetchTables,
    fetchDbStats,
    fetchTableSchema,
    fetchTableData
  }
}
