import { ipcMain, type IpcMainInvokeEvent } from "electron";
import { reportError } from "@/lib/errors";

type InvokeHandler = (
  event: IpcMainInvokeEvent,
  ...args: unknown[]
) => Promise<unknown> | unknown;

/**
 * Wraps `ipcMain.handle` so handler failures log with full stack in main and
 * re-throw a sanitized message to the renderer.
 */
export function safeHandle(channel: string, handler: InvokeHandler): void {
  ipcMain.handle(channel, async (event, ...args) => {
    try {
      return await handler(event, ...(args as unknown[]));
    } catch (err) {
      reportError(err, { scope: `ipc.${channel}` });
      const message = err instanceof Error ? err.message : "IPC error";
      throw new Error(message);
    }
  });
}
