#Requires -Version 7.4

function Invoke-vSEALServiceOperation {
    <#
    .SYNOPSIS
        Internal helper for starting/stopping services with dependencies.

    .DESCRIPTION
        Handles service start/stop operations including dependent services
        and pending state handling.

    .PARAMETER Name
        The service name.

    .PARAMETER Operation
        'Start' or 'Stop'.

    .PARAMETER SkipDependentServices
        Skip processing dependent services.

    .PARAMETER PendingStatusWait
        Time to wait for pending states to resolve.

    .PARAMETER PassThru
        Return the service object.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(Mandatory)]
        [ValidateSet('Start', 'Stop')]
        [string]$Operation,

        [switch]$SkipDependentServices,

        [TimeSpan]$PendingStatusWait = [TimeSpan]::FromSeconds(60),

        [switch]$PassThru
    )

    # Get the service object
    $service = Get-Service -Name $Name -ErrorAction Stop

    # Handle pending states
    $pendingStates = @{
        'ContinuePending' = 'Running'
        'PausePending'    = 'Paused'
        'StartPending'    = 'Running'
        'StopPending'     = 'Stopped'
    }

    if ($pendingStates.ContainsKey($service.Status.ToString())) {
        $desiredStatus = $pendingStates[$service.Status.ToString()]
        Write-vSEALLog "Waiting for service [$Name] to reach [$desiredStatus] from pending state [$($service.Status)]..." -Level VERBOSE
        $service.WaitForStatus($desiredStatus, $PendingStatusWait)
        $service.Refresh()
    }

    Write-vSEALLog "Service [$($service.ServiceName)] status: [$($service.Status)]" -Level VERBOSE

    # Process dependent services helper
    $processDependents = {
        param($svc, $op)
        if ($SkipDependentServices) { return }

        $targetStatus = if ($op -eq 'Start') { 'Running' } else { 'Stopped' }
        $dependents = Get-Service -Name $svc.ServiceName -DependentServices |
            Where-Object { $_.Status -ne $targetStatus }

        if (-not $dependents) {
            Write-vSEALLog "No dependent services require action." -Level VERBOSE
            return
        }

        foreach ($dep in $dependents) {
            Write-vSEALLog "$($op)ing dependent service [$($dep.ServiceName)]..." -Level VERBOSE
            try {
                if ($op -eq 'Stop') {
                    $null = $dep | Stop-Service -Force -WarningAction Ignore
                } else {
                    $null = $dep | Start-Service -WarningAction Ignore
                }
            } catch {
                Write-vSEALLog "Failed to $($op.ToLower()) dependent service [$($dep.ServiceName)]: $_" -Level WARNING
            }
        }
    }

    # Perform the operation
    if ($Operation -eq 'Stop' -and $service.Status -ne 'Stopped') {
        & $processDependents $service 'Stop'
        Write-vSEALLog "Stopping service [$($service.ServiceName)]..." -Level VERBOSE
        $service = $service | Stop-Service -PassThru -Force -WarningAction Ignore
    }
    elseif ($Operation -eq 'Start' -and $service.Status -ne 'Running') {
        Write-vSEALLog "Starting service [$($service.ServiceName)]..." -Level VERBOSE
        $service = $service | Start-Service -PassThru -WarningAction Ignore
        & $processDependents $service 'Start'
    }

    if ($PassThru) {
        return $service
    }
}
