@echo off
:: ============================================================
::  DeployPro — Install as Windows Service
::  Requires: Node.js installed, Run as Administrator
:: ============================================================

NET SESSION >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
    echo Requesting administrator privileges...
    powershell -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /B
)

cd /d "%~dp0"

echo.
echo  ============================================================
echo   DeployPro ^| Windows Service Installer
echo  ============================================================
echo.

:: Check Node.js
where node >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
    echo  [ERROR] Node.js is not installed or not in PATH.
    echo  Download from https://nodejs.org/
    echo.
    pause
    exit /B 1
)

FOR /F "tokens=*" %%V IN ('node --version') DO SET NODE_VER=%%V
echo  Node.js version: %NODE_VER%
echo  Install path   : %~dp0
echo.

:: Install npm dependencies if needed
IF NOT EXIST "node_modules\node-windows\" (
    echo  [1/2] Installing dependencies (including node-windows)...
    call npm install
    IF %ERRORLEVEL% NEQ 0 (
        echo  [ERROR] npm install failed.
        pause
        exit /B 1
    )
    echo  Dependencies installed.
    echo.
) ELSE (
    echo  [1/2] Dependencies already installed.
    echo.
)

:: Install the Windows service
echo  [2/2] Installing Windows service...
echo.
node service\install.js

IF %ERRORLEVEL% EQU 0 (
    echo.
    echo  ============================================================
    echo   SUCCESS — DeployPro is now running as a Windows Service
    echo  ============================================================
    echo.
    echo   Web UI  : http://localhost:7070
    echo   Service : DeployPro  (auto-starts with Windows)
    echo.
    echo   Commands:
    echo     Start   ^>  net start deploypro.exe
    echo     Stop    ^>  net stop  deploypro.exe
    echo     Status  ^>  sc query  deploypro.exe
    echo     Remove  ^>  uninstall-service.bat
    echo.
    timeout /t 3 >nul
    start "" "http://localhost:7070"
) ELSE (
    echo.
    echo  [ERROR] Service installation failed. See output above.
)

echo.
pause
