import apiClient from './client'

export interface BaculaCapabilityHistory {
  backup_types: string[]
  source: string
  requested_by?: string
  requested_at: string
  notes?: string
}

export interface BaculaClient {
  id: string
  hostname: string
  ip_address: string
  agent_version: string
  status: string
  backup_types: string[]
  pending_backup_types?: string[]
  pending_requested_by?: string
  pending_requested_at?: string
  pending_notes?: string
  metadata?: Record<string, unknown>
  registered_by: string
  last_seen?: string
  created_at: string
  updated_at: string
  capability_history?: BaculaCapabilityHistory[]
}

export interface RegisterBaculaClientRequest {
  hostname: string
  ip_address: string
  agent_version?: string
  backup_types: string[]
  status?: string
  metadata?: Record<string, string>
}

export interface UpdateCapabilitiesRequest {
  backup_types: string[]
  notes?: string
}

export interface PendingBaculaUpdate {
  backup_types: string[]
  requested_by?: string
  requested_at: string
  notes?: string
}

export const baculaApi = {
  listClients: async (): Promise<BaculaClient[]> => {
    const response = await apiClient.get<BaculaClient[]>('/bacula/clients')
    return response.data
  },

  getClient: async (id: string): Promise<BaculaClient> => {
    const response = await apiClient.get<BaculaClient>(`/bacula/clients/${id}`)
    return response.data
  },

  registerClient: async (payload: RegisterBaculaClientRequest): Promise<BaculaClient> => {
    const response = await apiClient.post<BaculaClient>('/bacula/clients/register', payload)
    return response.data
  },

  updateCapabilities: async (id: string, payload: UpdateCapabilitiesRequest): Promise<PendingBaculaUpdate> => {
    const response = await apiClient.post<PendingBaculaUpdate>(`/bacula/clients/${id}/capabilities`, payload)
    return response.data
  },

  getPendingUpdate: async (id: string): Promise<PendingBaculaUpdate | null> => {
    const response = await apiClient.get<PendingBaculaUpdate>(`/bacula/clients/${id}/pending-update`)
    if (response.status === 204) {
      return null
    }
    return response.data
  },

  ping: async (id: string, status?: string): Promise<void> => {
    await apiClient.post(`/bacula/clients/${id}/ping`, { status })
  },
}
