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

/// <summary>Service collection extensions for worker process management.</summary>
public static class WorkerServiceCollectionExtensions
{
    /// <summary>Registers worker process launcher and factory services.</summary>
    /// <param name="services">Service collection to register services.</param>
    /// <returns>The same service collection, for chaining.</returns>
    public static IServiceCollection AddWorkerProcessLauncher(this IServiceCollection services)
    {
        services.AddSingleton<IWorkerProcessFactory, SystemWorkerProcessFactory>();
        services.AddSingleton<IWorkerStartupProbe, WorkerProcessStartedProbe>();
        services.AddSingleton<IWorkerProcessLauncher, WorkerProcessLauncher>();

        // Terminate workers leaked by a previous unclean gateway run before the
        // server accepts sessions. Registered ahead of AddGatewaySessions so the
        // cleanup hosted service starts before the session subsystem.
        services.AddSingleton<IRunningProcessInspector, SystemRunningProcessInspector>();
        services.AddSingleton<OrphanWorkerTerminator>();
        services.AddHostedService<OrphanWorkerCleanupHostedService>();

        return services;
    }
}
