import { ipcMain, app, BrowserWindow } from 'electron';
import log from 'electron-log';
import { settingsStore, Settings } from '../store';
import { actionsStore } from '../actions-store';

/**
 * Register settings, app, and actions-related IPC handlers
 */
export function registerSettingsHandlers(): void {
  // Settings handlers
  ipcMain.handle('settings:get-all', async () => {
    return settingsStore.getAll();
  });

  ipcMain.handle('settings:get-theme', async () => {
    return settingsStore.get('theme');
  });

  ipcMain.handle('settings:get-multi-deploy', async () => {
    return settingsStore.get('multiDeploy');
  });

  ipcMain.handle('settings:set', async (_event, key: keyof Settings, value: any) => {
    settingsStore.set(key, value);

    // Broadcast theme changes to all windows
    if (key === 'theme') {
      log.info(`Broadcasting theme change to all windows: ${value}`);
      BrowserWindow.getAllWindows().forEach(window => {
        window.webContents.send('theme-changed', value);
      });
    }
  });

  // App handlers
  ipcMain.handle('app:get-version', async () => {
    return app.getVersion();
  });

  // Actions handlers
  ipcMain.handle('actions:get-all', async () => {
    try {
      return actionsStore.getAll();
    } catch (error) {
      log.error('Error getting actions:', error);
      throw error;
    }
  });

  ipcMain.handle('actions:get', async (_event, id: string) => {
    try {
      return actionsStore.get(id);
    } catch (error) {
      log.error('Error getting action:', error);
      throw error;
    }
  });

  ipcMain.handle('actions:delete', async (_event, id: string) => {
    try {
      actionsStore.delete(id);
    } catch (error) {
      log.error('Error deleting action:', error);
      throw error;
    }
  });

  ipcMain.handle('actions:clear', async () => {
    try {
      actionsStore.clear();
    } catch (error) {
      log.error('Error clearing actions:', error);
      throw error;
    }
  });

  log.info('Settings and actions handlers registered');
}
