/**
 * 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'
import type { PaginatedResponse } from '@/types/api'

export interface ServerBrief {
  id: number
  name: string
  domain?: string
  target_path?: string
  category?: string | null
  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; all?: boolean }) {
    loading.value = true
    try {
      const perPage = opts?.perPage ?? 200
      if (!opts?.all) {
        const res = await http.getList<ServerBrief>('/servers/', { per_page: perPage })
        servers.value = res.items
        return
      }
      const all: ServerBrief[] = []
      let page = 1
      let pages = 1
      do {
        const res = await http.get<PaginatedResponse<ServerBrief>>('/servers/', {
          page,
          per_page: perPage,
        })
        all.push(...(res.items || []))
        pages = res.pages ?? 1
        page += 1
      } while (page <= pages)
      servers.value = all
    } catch (e: unknown) {
      servers.value = []
      snackbar(formatApiError(e, '加载服务器列表失败'), 'error')
    } finally {
      loading.value = false
    }
  }

  return { servers, loading, loadServers }
}
