/**
 * useServerList composable
 *
 * Fetches a flat server list (id + name) for dropdowns/selects.
 * Eliminates the identical loadServers() pattern in 5+ pages.
 */
import { ref } from 'vue'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import { formatApiError } from '@/utils/apiError'

export interface ServerBrief {
  id: number
  name: string
  domain?: string
  target_path?: string
  is_online?: boolean
  status?: string
}

export function useServerList() {
  const servers = ref<ServerBrief[]>([])
  const loading = ref(false)
  const snackbar = useSnackbar()

  async function loadServers(opts?: { perPage?: number }) {
    loading.value = true
    try {
      const res = await http.getList<ServerBrief>('/servers/', {
        per_page: opts?.perPage ?? 200,
      })
      servers.value = res.items
    } catch (e: unknown) {
      servers.value = []
      snackbar(formatApiError(e, '加载服务器列表失败'), 'error')
    } finally {
      loading.value = false
    }
  }

  return { servers, loading, loadServers }
}
