import apiClient from './client'

export interface NetworkInterface {
  name: string
  ip_address: string
  subnet: string
  status: string // "Connected" or "Down"
  speed: string // e.g., "10 Gbps", "1 Gbps"
  role: string // "Management", "ISCSI", or empty
  gateway?: string
  dns1?: string
  dns2?: string
}

export interface UpdateNetworkInterfaceRequest {
  ip_address: string
  subnet: string
  gateway?: string
  dns1?: string
  dns2?: string
  role?: string
}

export interface SaveNTPSettingsRequest {
  timezone: string
  ntp_servers: string[]
}

export interface NTPSettings {
  timezone: string
  ntp_servers: string[]
}

export interface ServiceStatus {
  name: string
  active_state: string // "active", "inactive", "activating", "deactivating", "failed"
  sub_state: string
  load_state: string
  description: string
  since?: string
}

export interface SystemLogEntry {
  time: string
  level: string
  source: string
  message: string
}

export interface NetworkDataPoint {
  time: string
  inbound: number // Mbps
  outbound: number // Mbps
}

export const systemAPI = {
  listNetworkInterfaces: async (): Promise<NetworkInterface[]> => {
    const response = await apiClient.get<{ interfaces: NetworkInterface[] | null }>('/system/interfaces')
    return response.data.interfaces || []
  },
  updateNetworkInterface: async (name: string, data: UpdateNetworkInterfaceRequest): Promise<NetworkInterface> => {
    const response = await apiClient.put<{ interface: NetworkInterface }>(`/system/interfaces/${name}`, data)
    return response.data.interface
  },
  getNTPSettings: async (): Promise<NTPSettings> => {
    const response = await apiClient.get<{ settings: NTPSettings }>('/system/ntp')
    return response.data.settings
  },
  saveNTPSettings: async (data: SaveNTPSettingsRequest): Promise<void> => {
    await apiClient.post('/system/ntp', data)
  },
  listServices: async (): Promise<ServiceStatus[]> => {
    const response = await apiClient.get<{ services: ServiceStatus[] }>('/system/services')
    return response.data.services || []
  },
  restartService: async (name: string): Promise<void> => {
    await apiClient.post(`/system/services/${name}/restart`)
  },
  getSystemLogs: async (limit: number = 30): Promise<SystemLogEntry[]> => {
    const response = await apiClient.get<{ logs: SystemLogEntry[] }>(`/system/logs?limit=${limit}`)
    return response.data.logs || []
  },
  getNetworkThroughput: async (duration: string = '5m'): Promise<NetworkDataPoint[]> => {
    const response = await apiClient.get<{ data: NetworkDataPoint[] }>(`/system/network/throughput?duration=${duration}`)
    return response.data.data || []
  },
  getManagementIPAddress: async (): Promise<string> => {
    const response = await apiClient.get<{ ip_address: string }>('/system/management-ip')
    return response.data.ip_address
  },
}

