import api from './api'

export interface NetworkNode {
  id: string
  name: string
  location: string
  ipAddress: string
  port: number
  apiKey: string
  isOnline: boolean
  lastSync: Date | null
  lastPing: Date | null
  type: 'admin' | 'local'
}

export interface SyncSettings {
  autoSyncInterval: string
  conflictResolution: 'admin' | 'newest' | 'manual'
  syncEmployees: boolean
  syncSkills: boolean
  syncUsers: boolean
  syncSettings: boolean
  bandwidthLimit: number | null
}

export const networkApi = {
  // Network nodes
  getNodes: async (): Promise<NetworkNode[]> => {
    const response = await api.get('/network/nodes')
    return response.data.data
  },

  createNode: async (node: Partial<NetworkNode>): Promise<{ id: string; apiKey: string }> => {
    const response = await api.post('/network/nodes', node)
    return response.data.data
  },

  updateNode: async (id: string, updates: Partial<NetworkNode>): Promise<void> => {
    await api.put(`/network/nodes/${id}`, updates)
  },

  deleteNode: async (id: string): Promise<void> => {
    await api.delete(`/network/nodes/${id}`)
  },

  pingNode: async (id: string): Promise<{ isOnline: boolean; lastPing: string; responseTime: number | null }> => {
    const response = await api.post(`/network/nodes/${id}/ping`)
    return response.data.data
  },

  // Sync settings
  getSyncSettings: async (): Promise<SyncSettings> => {
    const response = await api.get('/network/sync-settings')
    return response.data.data
  },

  updateSyncSettings: async (settings: Partial<SyncSettings>): Promise<void> => {
    await api.put('/network/sync-settings', settings)
  },

  // Sync operations
  triggerSync: async (nodeIds?: string[]): Promise<{ syncedAt: string; nodeCount: number | string }> => {
    const response = await api.post('/network/sync/trigger', { nodeIds })
    return response.data.data
  }
}