import { app } from 'electron';
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';

// Lancement au login. Windows/macOS : API Electron (login items). Linux : fichier .desktop dans
// ~/.config/autostart (pas d'API Electron fiable pour l'autostart Linux).

function desktopFile(): string {
  return join(homedir(), '.config', 'autostart', 'arboretum.desktop');
}

function desktopEntry(): string {
  const exec = process.env.APPIMAGE ?? app.getPath('exe');
  return `[Desktop Entry]
Type=Application
Name=Arboretum
Exec=${exec}
Terminal=false
X-GNOME-Autostart-enabled=true
`;
}

export function isAutoStartEnabled(): boolean {
  if (process.platform === 'linux') return existsSync(desktopFile());
  return app.getLoginItemSettings().openAtLogin;
}

export function setAutoStart(enabled: boolean): void {
  if (process.platform === 'linux') {
    if (enabled) {
      mkdirSync(dirname(desktopFile()), { recursive: true });
      writeFileSync(desktopFile(), desktopEntry());
    } else {
      try {
        unlinkSync(desktopFile());
      } catch {
        /* déjà absent */
      }
    }
    return;
  }
  app.setLoginItemSettings({ openAtLogin: enabled });
}
