/**
 * Electron Preload Script — Bradly Desktop App
 *
 * Exposes a safe, typed API to the renderer process via contextBridge.
 * The renderer (React app) can access these via `window.electronAPI`.
 *
 * Security: contextIsolation is enabled, nodeIntegration is disabled.
 * Only explicitly exposed functions are available to the renderer.
 */
import { contextBridge, ipcRenderer } from 'electron';

const electronAPI = {
  // ─── Platform Detection ───
  isElectron: true as const,
  platform: process.platform,

  // ─── Native Dialogs ───

  /** Show a native save dialog and return the chosen path */
  showSaveDialog: (options: Electron.SaveDialogOptions) =>
    ipcRenderer.invoke('dialog:save', options) as Promise<Electron.SaveDialogReturnValue>,

  /** Show a native open dialog and return the chosen paths */
  showOpenDialog: (options: Electron.OpenDialogOptions) =>
    ipcRenderer.invoke('dialog:open', options) as Promise<Electron.OpenDialogReturnValue>,

  // ─── File Operations ───

  /**
   * Save a rendered file to a user-chosen location.
   * Shows a native save dialog, then copies the rendered file to the chosen path.
   * 
   * @param renderUrl - The relative URL of the rendered file (e.g. /api/renders/abc.mp4)
   * @param defaultName - Suggested filename for the save dialog
   * @returns The saved file path, or null if cancelled
   */
  saveRenderedFile: (renderUrl: string, defaultName: string) =>
    ipcRenderer.invoke('file:saveRendered', renderUrl, defaultName) as Promise<string | null>,

  /**
   * Save raw binary data (e.g. a ZIP blob) to a user-chosen location.
   * Shows native save dialog, then writes the bytes.
   */
  saveBlobFile: (data: Uint8Array, defaultName: string, filters?: { name: string; extensions: string[] }[]) =>
    ipcRenderer.invoke('file:saveBlob', data, defaultName, filters) as Promise<string | null>,

  // ─── App Info ───
  getAppInfo: () =>
    ipcRenderer.invoke('app:info') as Promise<{
      version: string;
      name: string;
      userData: string;
      isPackaged: boolean;
    }>,
};

// Expose to the renderer process
contextBridge.exposeInMainWorld('electronAPI', electronAPI);

// TypeScript: Augment Window interface for consumers
export type ElectronAPI = typeof electronAPI;
