'use client'

import { useQuery } from '@tanstack/react-query'
import { apiGet } from '@/lib/api/client'
import type { SubscriptionTier, OrderStatus, UserSummary } from '@/types/api'

export type ServerStatus = 'online' | 'provisioning' | 'offline' | 'pending'

export interface Server {
  id: string
  domain: string
  tier: SubscriptionTier
  orderStatus: OrderStatus
  serverStatus: ServerStatus
  serverIp: string
  sshPort: number
  tools: string[]
  createdAt: Date
  serverReadyAt: Date | null
  completedAt: Date | null
  customer: UserSummary
}

export interface ServersResponse {
  servers: Server[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

export interface ServerFilters {
  status?: ServerStatus
  search?: string
  page?: number
  limit?: number
}

// API call
async function getServers(filters: ServerFilters = {}): Promise<ServersResponse> {
  return apiGet<ServersResponse>('/api/v1/admin/servers', {
    params: {
      status: filters.status,
      search: filters.search,
      page: filters.page,
      limit: filters.limit,
    },
  })
}

// Query keys
export const serverKeys = {
  all: ['servers'] as const,
  lists: () => [...serverKeys.all, 'list'] as const,
  list: (filters: ServerFilters) => [...serverKeys.lists(), filters] as const,
}

// Hook
export function useServers(filters: ServerFilters = {}) {
  return useQuery({
    queryKey: serverKeys.list(filters),
    queryFn: () => getServers(filters),
  })
}
