/**
 * useServerPagination composable
 *
 * Paginated server table with search debounce, page/perPage handlers.
 * Eliminates the identical pattern in ServersPage and DashboardPage.
 */
import { ref, onUnmounted } from 'vue'
import { http } from '@/api'
import type { ServerApiItem } from '@/types/api'
import type { PaginatedResponse } from '@/types/api'

export function useServerPagination() {
  const servers = ref<ServerApiItem[]>([])
  const loading = ref(false)
  const page = ref(1)
  const itemsPerPage = ref(20)
  const total = ref(0)
  const search = ref('')

  async function loadServers() {
    loading.value = true
    try {
      const res = await http.get<PaginatedResponse<ServerApiItem>>('/servers/', {
        page: page.value,
        per_page: itemsPerPage.value,
        search: search.value || undefined,
      })
      servers.value = res.items || []
      total.value = res.total || 0
    } catch (e) {
      servers.value = []
      total.value = 0
      throw e  // Let callers handle the error display
    } finally {
      loading.value = false
    }
  }

  let searchTimer: ReturnType<typeof setTimeout>
  onUnmounted(() => clearTimeout(searchTimer))
  function onSearch() {
    clearTimeout(searchTimer)
    searchTimer = setTimeout(() => { page.value = 1; loadServers() }, 300)
  }

  function onPageChange(p: number) {
    page.value = p
    loadServers()
  }

  function onItemsPerPageChange(n: number) {
    itemsPerPage.value = n
    page.value = 1
    loadServers()
  }

  return {
    servers, loading, page, itemsPerPage, total, search,
    loadServers, onSearch, onPageChange, onItemsPerPageChange,
  }
}
