import { contextBridge, ipcRenderer } from 'electron';
import type { Settings, SystemStatus, DockerStatus, InstallResult } from '../renderer/types';

// Inline helper to avoid module resolution issues in preload context
function createOutputListener(channel: string) {
  return (callback: (output: string) => void): (() => void) => {
    const listener = (_event: any, output: string) => callback(output);
    ipcRenderer.on(channel, listener);
    return () => {
      ipcRenderer.removeListener(channel, listener);
    };
  };
}

// Expose protected methods that allow the renderer process to use
// ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld('settingsAPI', {
  getSettings: async (): Promise<Settings> => {
    return ipcRenderer.invoke('settings:get-all');
  },

  setSetting: async <K extends keyof Settings>(
    key: K,
    value: Settings[K]
  ): Promise<void> => {
    return ipcRenderer.invoke('settings:set', key, value);
  },

  getVersion: async (): Promise<string> => {
    return ipcRenderer.invoke('app:get-version');
  },

  getSystemStatus: async (): Promise<SystemStatus> => {
    return ipcRenderer.invoke('system:get-status');
  },

  checkDockerStatus: async (): Promise<DockerStatus> => {
    return ipcRenderer.invoke('system:check-docker');
  },

  installDocker: async (): Promise<InstallResult> => {
    return ipcRenderer.invoke('system:install-docker');
  },

  updateDocker: async (): Promise<InstallResult> => {
    return ipcRenderer.invoke('system:update-docker');
  },

  reinstallDocker: async (): Promise<InstallResult> => {
    return ipcRenderer.invoke('system:reinstall-docker');
  },

  openDocker: async (): Promise<{ success: boolean; message?: string }> => {
    return ipcRenderer.invoke('system:open-docker');
  },

  onInstallOutput: createOutputListener('docker:install-output'),

  onUpdateOutput: createOutputListener('docker:update-output'),

  onReinstallOutput: createOutputListener('docker:reinstall-output'),

  getOnboardingState: async () => {
    return ipcRenderer.invoke('onboarding:get-state');
  },

  onThemeChange: createOutputListener('theme-changed')
});
