import { contextBridge, ipcRenderer } from 'electron';

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);
  };
}

import type { InstallResult, BackupEntry } from '../renderer/types';

try {
  contextBridge.exposeInMainWorld('backupRestoreAPI', {
    getContainers: async (): Promise<string[]> =>
      ipcRenderer.invoke('backup-restore:get-containers'),

    getBackups: async (): Promise<BackupEntry[]> =>
      ipcRenderer.invoke('backup-restore:get-backups'),

    setDefaultBackup: async (id: string, isDefault: boolean): Promise<void> =>
      ipcRenderer.invoke('backup-restore:set-default', id, isDefault),

    deleteBackup: async (id: string): Promise<void> =>
      ipcRenderer.invoke('backup-restore:delete-backup', id),

    createBackup: async (options: { containerName: string; notes: string }): Promise<InstallResult> =>
      ipcRenderer.invoke('backup-restore:create-backup', options),

    onBackupOutput: createOutputListener('backup-restore:backup-output'),

    restoreBackup: async (options: { backupFilePath: string; containerName: string }): Promise<InstallResult> =>
      ipcRenderer.invoke('backup-restore:restore-backup', options),

    onRestoreOutput: createOutputListener('backup-restore:restore-output'),

    selectBackupFile: async (): Promise<string | null> =>
      ipcRenderer.invoke('backup-restore:select-backup-file'),

    exportBackup: async (backupId: string): Promise<InstallResult> =>
      ipcRenderer.invoke('backup-restore:export-backup', backupId),

    importBackup: async (exportedZipPath: string): Promise<InstallResult> =>
      ipcRenderer.invoke('backup-restore:import-backup', exportedZipPath),

    selectExportFile: async (): Promise<string | null> =>
      ipcRenderer.invoke('backup-restore:select-export-file'),

    getTheme: async (): Promise<string> =>
      ipcRenderer.invoke('settings:get-theme'),

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

  console.log('[Backup Restore Preload] API exposed successfully');
} catch (error) {
  console.error('[Backup Restore Preload] CRITICAL ERROR during API exposure:', error);
  throw error;
}
