namespace ZB.MOM.WW.MxGateway.Server.Workers;

/// <summary>
///     Hosted service that terminates leftover MXAccess worker processes once on
///     gateway startup, before the server begins accepting sessions.
/// </summary>
public sealed class OrphanWorkerCleanupHostedService(
    OrphanWorkerTerminator terminator,
    ILogger<OrphanWorkerCleanupHostedService> logger) : IHostedService
{
    /// <inheritdoc />
    public Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            terminator.TerminateOrphans();
        }
        catch (Exception exception)
        {
            // Orphan cleanup is best-effort; a failure here must not prevent
            // the gateway from starting.
            logger.LogWarning(exception, "Orphan worker cleanup failed on startup.");
        }

        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
