import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { DatabaseConnection, TableInfo, JoinDefinition } from '../types'
import { configApi } from '../services/configApi'

export const useConfigStore = defineStore('config', () => {
  const connections = ref<DatabaseConnection[]>([])
  const tables = ref<TableInfo[]>([])
  const joins = ref<JoinDefinition[]>([])
  const loading = ref(false)

  async function fetchConnections() {
    const { data } = await configApi.listConnections()
    connections.value = data
  }

  async function fetchTables() {
    const { data } = await configApi.listTables()
    tables.value = data
  }

  async function fetchJoins() {
    const { data } = await configApi.listJoins()
    joins.value = data
  }

  async function fetchAll() {
    loading.value = true
    try {
      await Promise.all([fetchConnections(), fetchTables(), fetchJoins()])
    } finally {
      loading.value = false
    }
  }

  return {
    connections, tables, joins, loading,
    fetchConnections, fetchTables, fetchJoins, fetchAll,
  }
})
