const { autoUpdater } = require('electron-updater');
const log = require('electron-log');

autoUpdater.logger = log;
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;

function checkForUpdates(splashWindow) {
  return new Promise((resolve) => {
    function sendToSplash(js) {
      if (splashWindow && !splashWindow.isDestroyed()) {
        splashWindow.webContents.executeJavaScript(js).catch(() => {});
      }
    }

    autoUpdater.on('checking-for-update', () => {
      sendToSplash('setStatus("Checking for updates...")');
    });

    autoUpdater.on('update-available', () => {
      sendToSplash('setStatus("Downloading update...")');
      autoUpdater.downloadUpdate();
    });

    autoUpdater.on('download-progress', (progress) => {
      const percent = Math.round(progress.percent);
      sendToSplash(`setProgress(${percent})`);
      sendToSplash(`setStatus("Downloading update... ${percent}%")`);
    });

    autoUpdater.on('update-downloaded', () => {
      sendToSplash('setStatus("Installing update...")');
      sendToSplash('setProgress(100)');
      setTimeout(() => {
        autoUpdater.quitAndInstall();
      }, 1500);
    });

    autoUpdater.on('update-not-available', () => {
      sendToSplash('setStatus("Up to date!")');
      sendToSplash('hideProgress()');
      setTimeout(() => resolve(false), 1000);
    });

    autoUpdater.on('error', (err) => {
      log.error('Auto-updater error:', err);
      sendToSplash('setStatus("Update check failed")');
      sendToSplash('hideProgress()');
      setTimeout(() => resolve(false), 2000);
    });

    autoUpdater.checkForUpdates().catch((err) => {
      log.error('checkForUpdates failed:', err);
      sendToSplash('setStatus("Update check failed")');
      sendToSplash('hideProgress()');
      setTimeout(() => resolve(false), 2000);
    });
  });
}

module.exports = { checkForUpdates };
