import { app, BrowserWindow } from "electron";
import { storeServiceInstance } from "../../main";

// Track if handlers have been initialized to prevent duplicates
let autoLaunchHandlersInitialized = false;

/**
 * Clean up existing auto-launch IPC handlers
 */
export function cleanupAutoLaunchHandlers(window: BrowserWindow) {
  try {
    // Remove auto-launch handlers
    window.webContents.ipc.removeHandler("auto-launch:get");
    window.webContents.ipc.removeHandler("auto-launch:set");

    autoLaunchHandlersInitialized = false;
    console.log("[AutoLaunch] Cleaned up existing IPC handlers");
  } catch (error) {
    // Ignore errors if handlers don't exist
    console.debug("[AutoLaunch] No existing handlers to clean up");
  }
}

export function registerAutoLaunchHandlers(window: BrowserWindow) {
  // Prevent duplicate handler registration
  if (autoLaunchHandlersInitialized) {
    console.warn("[AutoLaunch] Handlers already initialized, skipping registration...");
    return;
  }

  // Clean up any existing handlers first
  cleanupAutoLaunchHandlers(window);

  // Get current auto-launch setting
  window.webContents.ipc.handle("auto-launch:get", () => {
    const settings = app.getLoginItemSettings();
    return settings.openAtLogin;
  });

  // Set auto-launch setting
  window.webContents.ipc.handle("auto-launch:set", async (_, enabled: boolean) => {
    try {
      app.setLoginItemSettings({
        openAtLogin: enabled,
        openAsHidden: true,
      });
      // Store the preference
      storeServiceInstance.set("launchAtLogin", enabled);
      return true;
    } catch (error) {
      console.error("Failed to set auto-launch setting:", error);
      return false;
    }
  });

  autoLaunchHandlersInitialized = true;
  console.log("[AutoLaunch] All handlers registered successfully");
}
