import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ServerConnection, ServerConfig, ServerStats } from '@/types'
import { useApi } from '@/composables/useApi'

export const useServerStore = defineStore('server', () => {
  const connection = ref<ServerConnection | null>(null)
  const config = ref<ServerConfig | null>(null)
  const stats = ref<ServerStats | null>(null)
  const isLoading = ref(false)

  const api = useApi()

  async function fetchServer() {
    isLoading.value = true
    try {
      const data = await api.get<{ connection: ServerConnection | null; config: ServerConfig | null }>('/servers')
      connection.value = data.connection
      config.value = data.config
    } catch (e) {
      console.error('Failed to fetch server:', e)
    } finally {
      isLoading.value = false
    }
  }

  async function updateConfig(updates: Partial<ServerConfig>) {
    try {
      await api.put('/servers/config', updates)
      await fetchServer()
    } catch (e) {
      console.error('Failed to update config:', e)
      throw e
    }
  }

  async function sendCommand(command: string) {
    return api.post('/servers/command', { command })
  }

  async function startServer() {
    return api.post('/servers/start')
  }

  async function stopServer() {
    return api.post('/servers/stop')
  }

  async function restartServer() {
    return api.post('/servers/restart')
  }

  function updateStats(newStats: ServerStats) {
    stats.value = newStats
  }

  return {
    connection,
    config,
    stats,
    isLoading,
    fetchServer,
    updateConfig,
    sendCommand,
    startServer,
    stopServer,
    restartServer,
    updateStats,
  }
})
