import { contextBridge, ipcRenderer } from 'electron';
import type { ActionEntry } from '../main/actions-store';

// Inline helper to avoid module resolution issues in preload context
function createActionListener<T>(channel: string) {
  return (callback: (action: T) => void): (() => void) => {
    const listener = (_event: any, action: T) => callback(action);
    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('actionsAPI', {
  // Get all actions
  getAll: async (): Promise<ActionEntry[]> => {
    return ipcRenderer.invoke('actions:get-all');
  },

  // Get a specific action
  get: async (id: string): Promise<ActionEntry | undefined> => {
    return ipcRenderer.invoke('actions:get', id);
  },

  // Delete an action
  delete: async (id: string): Promise<void> => {
    return ipcRenderer.invoke('actions:delete', id);
  },

  // Clear all actions
  clear: async (): Promise<void> => {
    return ipcRenderer.invoke('actions:clear');
  },

  // Listen for new actions
  onActionAdded: createActionListener<ActionEntry>('action:added'),

  // Theme operations
  getTheme: async (): Promise<string> => {
    return ipcRenderer.invoke('settings:get-theme');
  },

  // Theme change listener
  onThemeChange: createActionListener<string>('theme-changed')
});
