using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

namespace StellaOps.Feedser.Core.Jobs;

public static class JobServiceCollectionExtensions
{
    public static JobSchedulerBuilder AddJobScheduler(this IServiceCollection services, Action<JobSchedulerOptions>? configure = null)
    {
        ArgumentNullException.ThrowIfNull(services);

        var optionsBuilder = services.AddOptions<JobSchedulerOptions>();
        if (configure is not null)
        {
            optionsBuilder.Configure(configure);
        }

        services.AddSingleton(sp => sp.GetRequiredService<IOptions<JobSchedulerOptions>>().Value);
        services.AddSingleton<JobDiagnostics>();
        services.TryAddSingleton(TimeProvider.System);
        services.AddSingleton<IJobCoordinator, JobCoordinator>();
        services.AddHostedService<JobSchedulerHostedService>();

        return new JobSchedulerBuilder(services);
    }
}
