using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

/// <summary>Hosted service that cleanly shuts down all gateway sessions on application shutdown.</summary>
public sealed class SessionShutdownHostedService(
    ISessionManager sessionManager,
    ILogger<SessionShutdownHostedService> logger) : IHostedService
{
    /// <inheritdoc />
    public Task StartAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        try
        {
            await sessionManager.ShutdownAsync(cancellationToken).ConfigureAwait(false);
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            logger.LogWarning("Gateway session shutdown was canceled by host shutdown timeout.");
        }
    }
}
