const fs = require("fs");
const path = require("path");

console.log("🎯 Creating Windows EXE Installer...");

// Create NSIS script for Windows installer
const nsisScript = `
; Siraya Printer Service Installer
; Created automatically

!include "MUI2.nsh"

; Basic settings
Name "Siraya Printer Service"
OutFile "SirayaPrinterSetup.exe"
InstallDir "$PROGRAMFILES\\SirayaPrinter"
RequestExecutionLevel admin

; Interface settings
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH

!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES

!insertmacro MUI_LANGUAGE "English"

Section "Main"
  ; Set output path
  SetOutPath "$INSTDIR"
  
  ; Copy all files
  File /r "source\\*.*"
  
  ; Install Node.js if not present
  ReadRegStr $0 HKLM "SOFTWARE\\Node.js" "InstallPath"
  ${If} $0 == ""
    MessageBox MB_YESNO "Node.js not found. Install it?" IDYES installNode
    Goto skipNode
    installNode:
      NSISdl::download "https://nodejs.org/dist/v18.18.0/node-v18.18.0-x64.msi" "$TEMP\\nodejs.msi"
      ExecWait 'msiexec /i "$TEMP\\nodejs.msi" /quiet /norestart'
    skipNode:
  ${EndIf}
  
  ; Run npm install
  nsExec::ExecToLog 'npm install --production'
  
  ; Create Windows Service
  nsExec::ExecToLog 'node install-service.js'
  
  ; Create shortcuts
  CreateDirectory "$SMPROGRAMS\\Siraya Printer"
  CreateShortCut "$SMPROGRAMS\\Siraya Printer\\Control Panel.lnk" "http://localhost:5000"
  CreateShortCut "$SMPROGRAMS\\Siraya Printer\\Start Service.lnk" "$INSTDIR\\start-service.js"
  CreateShortCut "$SMPROGRAMS\\Siraya Printer\\Uninstall.lnk" "$INSTDIR\\uninstall.exe"
  CreateShortCut "$DESKTOP\\Siraya Printer.lnk" "http://localhost:5000"
  
  ; Write uninstaller
  WriteUninstaller "$INSTDIR\\uninstall.exe"
SectionEnd

Section "Uninstall"
  ; Stop service
  nsExec::ExecToLog 'net stop SirayaPrinterService'
  nsExec::ExecToLog 'sc delete SirayaPrinterService'
  
  ; Remove files
  RMDir /r "$INSTDIR"
  
  ; Remove shortcuts
  Delete "$SMPROGRAMS\\Siraya Printer\\*.*"
  RMDir "$SMPROGRAMS\\Siraya Printer"
  Delete "$DESKTOP\\Siraya Printer.lnk"
SectionEnd
`;

// Save NSIS script
fs.writeFileSync("installer.nsi", nsisScript);

console.log("📝 NSIS script created: installer.nsi");
console.log("\n📦 To create EXE installer:");
console.log("1. Install NSIS from: https://nsis.sourceforge.io/Download");
console.log("2. Run: makensis installer.nsi");
console.log("3. This creates: SirayaPrinterSetup.exe");
console.log("\n🎯 This EXE will:");
console.log("✓ Auto-install Node.js if needed");
console.log("✓ Install printer service");
console.log("✓ Create shortcuts");
console.log("✓ Run in background");
console.log("✓ Add firewall rule");
