// Disable no-unused-vars, broken for spread args
/* eslint no-unused-vars: off */
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

export type Channels = 'ipc-example';

const electronHandler = {
  ipcRenderer: {
    sendMessage(channel: Channels, ...args: unknown[]) {
      ipcRenderer.send(channel, ...args);
    },
    on(channel: Channels, func: (...args: unknown[]) => void) {
      const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
        func(...args);
      ipcRenderer.on(channel, subscription);

      return () => {
        ipcRenderer.removeListener(channel, subscription);
      };
    },
    once(channel: Channels, func: (...args: unknown[]) => void) {
      ipcRenderer.once(channel, (_event, ...args) => func(...args));
    },
    // kubectl commands
    executeKubectl: (command: string, kubeconfig?: string) =>
      ipcRenderer.invoke('execute-kubectl', command, kubeconfig),
    getNodesInfo: (kubeconfig?: string) =>
      ipcRenderer.invoke('get-nodes-info', kubeconfig),
    getNodeDetails: (nodeName: string, kubeconfig?: string) =>
      ipcRenderer.invoke('get-node-details', nodeName, kubeconfig),
    getNodePods: (nodeName: string, kubeconfig?: string) =>
      ipcRenderer.invoke('get-node-pods', nodeName, kubeconfig),
    getNodeMetrics: (nodeName: string, kubeconfig?: string) =>
      ipcRenderer.invoke('get-node-metrics', nodeName, kubeconfig),
    // Terminal functions
    startTerminalSession: (command: string) =>
      ipcRenderer.invoke('start-terminal-session', command),
    sendTerminalData: (sessionId: string, data: string) =>
      ipcRenderer.send('terminal-data', sessionId, data),
    killTerminalSession: (sessionId: string) =>
      ipcRenderer.invoke('kill-terminal-session', sessionId),
    onTerminalData: (sessionId: string, callback: (data: string) => void) => {
      const listener = (_event: any, id: string, data: string) => {
        if (id === sessionId) callback(data);
      };
      ipcRenderer.on('terminal-data', listener);
      return () => ipcRenderer.removeListener('terminal-data', listener);
    },
    onTerminalExit: (sessionId: string, callback: (code: number) => void) => {
      const listener = (_event: any, id: string, code: number) => {
        if (id === sessionId) callback(code);
      };
      ipcRenderer.on('terminal-exit', listener);
      return () => ipcRenderer.removeListener('terminal-exit', listener);
    },
    // Kubeconfig file operations
    selectKubeconfigFile: () => ipcRenderer.invoke('select-kubeconfig-file'),
    saveKubeconfigContent: (fileName: string, content: string) =>
      ipcRenderer.invoke('save-kubeconfig-content', fileName, content),
    validateKubeconfigCapabilities: (kubeconfigPath: string) =>
      ipcRenderer.invoke('validate-kubeconfig-capabilities', kubeconfigPath),
  },
};

contextBridge.exposeInMainWorld('electron', electronHandler);

export type ElectronHandler = typeof electronHandler;
