import { ipcMain, app, dialog, shell, BrowserWindow, Notification } from "electron";
import Store from "electron-store";

const store = new Store() as any;

export function setupIPC(mainWindow: BrowserWindow): void {
  // ── App Info ──
  ipcMain.handle("app:version", () => app.getVersion());
  ipcMain.handle("app:platform", () => process.platform);
  ipcMain.handle("app:isDev", () => !app.isPackaged);

  // ── Window Controls ──
  ipcMain.on("window:minimize", () => {
    mainWindow?.minimize();
  });

  ipcMain.on("window:maximize", () => {
    if (mainWindow?.isMaximized()) {
      mainWindow.unmaximize();
    } else {
      mainWindow?.maximize();
    }
  });

  ipcMain.on("window:close", () => {
    mainWindow?.close();
  });

  ipcMain.handle("window:isMaximized", () => {
    return mainWindow?.isMaximized() ?? false;
  });

  // ── File Dialogs ──
  ipcMain.handle("dialog:openFile", async (_event, options?) => {
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ["openFile"],
      ...options,
    });
    return result.canceled ? undefined : result.filePaths;
  });

  ipcMain.handle("dialog:saveFile", async (_event, options?) => {
    const result = await dialog.showSaveDialog(mainWindow, {
      ...options,
    });
    return result.canceled ? undefined : result.filePath;
  });

  // ── Notifications ──
  ipcMain.on("notification:show", (_event, { title, body }) => {
    if (Notification.isSupported()) {
      new Notification({ title, body }).show();
    }
  });

  // ── Shell ──
  ipcMain.on("shell:openExternal", (_event, url: string) => {
    shell.openExternal(url);
  });

  ipcMain.on("shell:openPath", (_event, path: string) => {
    shell.openPath(path);
  });

  // ── Persistent Store ──
  ipcMain.handle("store:get", (_event, key: string) => {
    return store.get(key);
  });

  ipcMain.handle("store:set", (_event, key: string, value: unknown) => {
    store.set(key, value);
  });

  ipcMain.handle("store:delete", (_event, key: string) => {
    store.delete(key);
  });
}
