import { contextBridge, ipcRenderer } from "electron";
import type { BglandsLauncherApi, LauncherSettings, LauncherSnapshot } from "./shared/contracts.js";

const api: BglandsLauncherApi = {
  getSnapshot: () => ipcRenderer.invoke("bglands:get-snapshot") as Promise<LauncherSnapshot>,
  connectMicrosoft: () => ipcRenderer.invoke("bglands:connect") as Promise<void>,
  cancelMicrosoftLogin: () => ipcRenderer.invoke("bglands:cancel-connect") as Promise<void>,
  openMicrosoftLogin: () => ipcRenderer.invoke("bglands:open-login") as Promise<void>,
  disconnectMicrosoft: () => ipcRenderer.invoke("bglands:disconnect") as Promise<void>,
  play: () => ipcRenderer.invoke("bglands:play") as Promise<void>,
  repair: () => ipcRenderer.invoke("bglands:repair") as Promise<void>,
  openLogs: () => ipcRenderer.invoke("bglands:open-logs") as Promise<void>,
  openSupport: () => ipcRenderer.invoke("bglands:open-support") as Promise<void>,
  saveSettings: (settings: LauncherSettings) => ipcRenderer.invoke("bglands:save-settings", settings) as Promise<void>,
  configureMicrosoft: (clientId: string) => ipcRenderer.invoke("bglands:configure-microsoft", clientId) as Promise<void>,
  openMicrosoftSetup: () => ipcRenderer.invoke("bglands:open-microsoft-setup") as Promise<void>,
  onSnapshot: (listener: (snapshot: LauncherSnapshot) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, snapshot: LauncherSnapshot): void => listener(snapshot);
    ipcRenderer.on("bglands:snapshot", handler);
    return () => ipcRenderer.removeListener("bglands:snapshot", handler);
  },
};

contextBridge.exposeInMainWorld("bglands", Object.freeze(api));
