const { contextBridge, ipcRenderer } = require('electron');
const packageJson = require('../package.json');

contextBridge.exposeInMainWorld('wifiApi', {
  getStatus: () => ipcRenderer.invoke('wifi:get-status'),
  scan: () => ipcRenderer.invoke('wifi:scan'),
  connect: ({ ssid, password }) => ipcRenderer.invoke('wifi:connect', { ssid, password })
});

contextBridge.exposeInMainWorld('rfidApi', {
  getStatus: () => ipcRenderer.invoke('rfid:get-status'),
  onUpdate: (callback) => {
    if (typeof callback !== 'function') {
      return () => {};
    }
    const channel = 'rfid:update';
    const handler = (_event, payload) => {
      callback(payload);
    };
    ipcRenderer.on(channel, handler);
    return () => {
      ipcRenderer.removeListener(channel, handler);
    };
  }
});

contextBridge.exposeInMainWorld('scaleApi', {
  getStatus: () => ipcRenderer.invoke('scale:get-status'),
  getConfig: () => ipcRenderer.invoke('scale:get-config'),
  setConfig: (config) => ipcRenderer.invoke('scale:set-config', config),
  calibrate: () => ipcRenderer.invoke('scale:calibrate'),
  clearTare: () => ipcRenderer.invoke('scale:clear-tare'),
  calibrateKnownWeight: (knownWeightKg) =>
    ipcRenderer.invoke('scale:calibrate-known-weight', { knownWeightKg }),
  setupInit: () => ipcRenderer.invoke('scale:setup-init'),
  setupCaptureStable: () => ipcRenderer.invoke('scale:setup-capture-stable'),
  setupApplyGain: ({ knownWeightKg, zeroRaw, loadRaw }) =>
    ipcRenderer.invoke('scale:setup-apply-gain', { knownWeightKg, zeroRaw, loadRaw }),
  setupSaveDeadWeight: () => ipcRenderer.invoke('scale:setup-save-dead-weight'),
  setupClearOffsets: ({ preserveDeadWeight }) =>
    ipcRenderer.invoke('scale:setup-clear-offsets', { preserveDeadWeight }),
  setupReadState: () => ipcRenderer.invoke('scale:setup-read-state'),
  getSetupLogPath: () => ipcRenderer.invoke('scale:get-setup-log-path'),
  openSetupLog: () => ipcRenderer.invoke('scale:open-setup-log'),
  listPorts: () => ipcRenderer.invoke('scale:list-ports'),
  listStablePorts: () => ipcRenderer.invoke('scale:list-stable-ports'),
  onSetupLog: (callback) => {
    if (typeof callback !== 'function') {
      return () => {};
    }
    const channel = 'scale:setup-log';
    const handler = (_event, payload) => {
      callback(payload);
    };
    ipcRenderer.on(channel, handler);
    return () => {
      ipcRenderer.removeListener(channel, handler);
    };
  },
  onUpdate: (callback) => {
    if (typeof callback !== 'function') {
      return () => {};
    }
    const channel = 'scale:update';
    const handler = (_event, payload) => {
      callback(payload);
    };
    ipcRenderer.on(channel, handler);
    return () => {
      ipcRenderer.removeListener(channel, handler);
    };
  }
});

contextBridge.exposeInMainWorld('appApi', {
  getVersion: () => packageJson.version,
  restartWithUpdate: () => ipcRenderer.invoke('app:restart-with-update')
});
