import { contextBridge, ipcRenderer } from 'electron';

const api = {
  // Auth
  register: (email: string, password: string) =>
    ipcRenderer.invoke('auth:register', email, password),
  login: (email: string, password: string) =>
    ipcRenderer.invoke('auth:login', email, password),
  getMe: () => ipcRenderer.invoke('auth:me'),

  // Devices
  registerDevice: (data: { device_name: string; device_fingerprint: string; public_key: string }) =>
    ipcRenderer.invoke('device:register', data),
  listDevices: () => ipcRenderer.invoke('device:list'),
  updateDeviceStatus: (id: number, status: string) =>
    ipcRenderer.invoke('device:updateStatus', id, status),
  deleteDevice: (id: number) => ipcRenderer.invoke('device:delete', id),

  // Nodes
  listNodes: () => ipcRenderer.invoke('node:list'),
  getAvailableNodes: () => ipcRenderer.invoke('node:available'),

  // Connections
  requestConnection: (data: { device_id: number; node_id: number }) =>
    ipcRenderer.invoke('connection:request', data),
  disconnect: (deviceId: number) =>
    ipcRenderer.invoke('connection:disconnect', deviceId),
  getConnectionLogs: () => ipcRenderer.invoke('connection:logs'),

  // Relay
  connectToRelay: (host: string, port: number, token: string, deviceId: number) =>
    ipcRenderer.invoke('relay:connect', host, port, token, deviceId),
  sendRelayMessage: (targetDeviceId: number, payload: string) =>
    ipcRenderer.invoke('relay:send', targetDeviceId, payload),
  disconnectFromRelay: () => ipcRenderer.invoke('relay:disconnect'),

  // Events from main → renderer
  onRelayMessage: (callback: (msg: any) => void) => {
    ipcRenderer.on('relay:message', (_event, msg) => callback(msg));
  },
  onRelayStatus: (callback: (status: string) => void) => {
    ipcRenderer.on('relay:status', (_event, status) => callback(status));
  },
  removeRelayListeners: () => {
    ipcRenderer.removeAllListeners('relay:message');
    ipcRenderer.removeAllListeners('relay:status');
  },
};

contextBridge.exposeInMainWorld('electronAPI', api);
