@echo off
setlocal enabledelayedexpansion

set SERVICE_NAME=XYZ Print Service

REM Get the script directory and resolve EXE path
set "SCRIPT_DIR=%~dp0"
set "PROJECT_ROOT=%SCRIPT_DIR%.."
set "EXE_PATH=%PROJECT_ROOT%\publish\XYZ.PrintService.exe"

REM Convert to absolute path
for %%A in ("%EXE_PATH%") do set "EXE_PATH=%%~fA"

echo ========================================
echo Installing XYZ Print Service
echo ========================================
echo.
echo Service Name: %SERVICE_NAME%
echo Executable: %EXE_PATH%
echo.

REM Check for admin privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
  echo ERROR: This script must be run as Administrator
  echo.
  echo Right-click on install-service.bat and select
  echo "Run as administrator"
  echo.
  pause
  exit /b 1
)

REM Check if EXE exists
if not exist "%EXE_PATH%" (
  echo ERROR: Service executable not found!
  echo.
  echo Expected location: %EXE_PATH%
  echo.
  echo Please run 'scripts\publish.bat' first to build the service
  echo.
  pause
  exit /b 1
)

echo Executable found: %EXE_PATH%
echo.

REM Check if service already exists
sc query "%SERVICE_NAME%" >nul 2>&1
if %errorlevel% equ 0 (
  echo Service already exists. Stopping and removing...
  sc stop "%SERVICE_NAME%" >nul 2>&1
  timeout /t 2 /nobreak >nul
  sc delete "%SERVICE_NAME%" >nul 2>&1
  timeout /t 1 /nobreak >nul
)

echo Installing "%SERVICE_NAME%"...
sc create "%SERVICE_NAME%" binPath= "\"%EXE_PATH%\"" start= auto DisplayName= "XYZ POS Print Service"
if %errorlevel% neq 0 (
  echo ERROR: Failed to create service
  exit /b 1
)

echo Starting service...
sc start "%SERVICE_NAME%"
if %errorlevel% neq 0 (
  echo WARNING: Service created but failed to start
  echo Check Windows Event Viewer for details
  exit /b 1
)

timeout /t 2 /nobreak >nul
sc query "%SERVICE_NAME%"

echo.
echo ========================================
echo Service installed and started successfully!
echo Service Name: %SERVICE_NAME%
echo Listening on: http://127.0.0.1:9101
echo ========================================

endlocal
