param(
    [string]$ServiceName = 'AbogadasLitoralScheduler',
    [string]$NssmPath = 'C:\nssm\win64\nssm.exe',
    [string]$PhpPath = 'C:\xampp\php\php.exe',
    [string]$ProjectPath = 'C:\Users\lucia\abogadaslitoral',
    [bool]$RemoveStartupLauncher = $true
)

$ErrorActionPreference = 'Stop'

function Test-Admin {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

if (-not (Test-Admin)) {
    throw 'Este script requiere PowerShell ejecutado como Administrador.'
}

if (-not (Test-Path $NssmPath)) {
    throw "No se encontro nssm.exe en: $NssmPath"
}

if (-not (Test-Path $PhpPath)) {
    throw "No se encontro php.exe en: $PhpPath"
}

if (-not (Test-Path $ProjectPath)) {
    throw "No se encontro la carpeta del proyecto en: $ProjectPath"
}

$artisanPath = Join-Path $ProjectPath 'artisan'
if (-not (Test-Path $artisanPath)) {
    throw "No se encontro artisan en: $artisanPath"
}

$stdoutLog = Join-Path $ProjectPath 'storage\logs\scheduler-service.log'
$stderrLog = Join-Path $ProjectPath 'storage\logs\scheduler-service-error.log'

$serviceExists = (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) -ne $null
if ($serviceExists) {
    & $NssmPath stop $ServiceName | Out-Null
    & $NssmPath remove $ServiceName confirm | Out-Null
}

& $NssmPath install $ServiceName $PhpPath "artisan schedule:work --no-interaction"
& $NssmPath set $ServiceName AppDirectory $ProjectPath
& $NssmPath set $ServiceName Start SERVICE_AUTO_START
& $NssmPath set $ServiceName DisplayName 'Laravel Scheduler - AbogadasLitoral'
& $NssmPath set $ServiceName Description 'Ejecuta php artisan schedule:work para tareas automaticas de Laravel.'
& $NssmPath set $ServiceName AppStdout $stdoutLog
& $NssmPath set $ServiceName AppStderr $stderrLog
& $NssmPath set $ServiceName AppRotateFiles 1
& $NssmPath set $ServiceName AppRotateOnline 1
& $NssmPath set $ServiceName AppRotateSeconds 86400
& $NssmPath set $ServiceName AppRotateBytes 1048576

Start-Service -Name $ServiceName

if ($RemoveStartupLauncher) {
    $startupLauncher = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup\abogadaslitoral-scheduler.vbs'
    if (Test-Path $startupLauncher) {
        Remove-Item $startupLauncher -Force
    }
}

Get-Service -Name $ServiceName | Select-Object Name, Status, StartType
