import { ref } from 'vue' import type { TableInfo, TableSchema, DbStats } from '@/types/database' const API_BASE = 'http://localhost:4101/api/database' export function useDatabaseApi() { const tables = ref([]) const tableSchema = ref([]) const tableData = ref([]) const dbStats = ref(null) const loading = ref(false) const error = ref(null) const totalRecords = ref(0) async function fetchTables() { loading.value = true error.value = null try { const res = await fetch(`${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 fetch(`${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 fetch(`${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 fetch(`${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 } }