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
{
    /// <summary>Terminates leftover orphan MXAccess worker processes once, best-effort, before the gateway starts accepting sessions.</summary>
    /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    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;
    }

    /// <summary>No-op; this service has no ongoing work to stop.</summary>
    /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
