import pkg from 'electron-updater';
import type { UpdateInfo } from 'electron-updater';
const { autoUpdater } = pkg;
import { app, BrowserWindow } from 'electron';

const updateCheckInterval = 4 * 60 * 60 * 1000; // 4 heures

let initialized = false;
let currentWindow: BrowserWindow | null = null;

export function initAutoUpdater(window: BrowserWindow): void {
  currentWindow = window;

  if (!app.isPackaged) {
    console.log('[AutoUpdater] Skipped in development mode');
    return;
  }

  // Si déjà initialisé, juste mettre à jour la fenêtre cible
  if (initialized) {
    console.log('[AutoUpdater] Window target updated');
    return;
  }

  initialized = true;

  // Config: télécharge auto, installe au quit
  autoUpdater.autoDownload = true;
  autoUpdater.autoInstallOnAppQuit = true;

  autoUpdater.on('checking-for-update', () => {
    console.log('[AutoUpdater] Checking for updates...');
  });

  autoUpdater.on('update-available', (info: UpdateInfo) => {
    console.log('[AutoUpdater] Update available:', info.version);
    currentWindow?.webContents.send('update:available', info.version);
  });

  autoUpdater.on('update-not-available', () => {
    console.log('[AutoUpdater] App is up to date');
  });

  autoUpdater.on('download-progress', (progress) => {
    const percent = Math.round(progress.percent);
    console.log(`[AutoUpdater] Downloading: ${percent}%`);
    currentWindow?.webContents.send('update:progress', percent);
  });

  autoUpdater.on('update-downloaded', (info: UpdateInfo) => {
    console.log('[AutoUpdater] Update ready:', info.version);
    currentWindow?.webContents.send('update:ready', info.version);
  });

  autoUpdater.on('error', (error: Error) => {
    console.error('[AutoUpdater] Error:', error.message);
  });

  // Check initial
  autoUpdater.checkForUpdates().catch((err) => {
    console.error('[AutoUpdater] Check failed:', err.message);
  });

  // Re-check périodique
  setInterval(() => {
    autoUpdater.checkForUpdates().catch((err) => {
      console.error('[AutoUpdater] Periodic check failed:', err.message);
    });
  }, updateCheckInterval);
}

// Pour forcer l'installation immédiate (optionnel, appelable depuis le renderer)
export function installUpdateNow(): void {
  autoUpdater.quitAndInstall(false, true);
}