using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.DependencyInjection;
using StellaOps.Feedser.Core.Jobs;
using StellaOps.Feedser.Source.Ru.Bdu.Configuration;

namespace StellaOps.Feedser.Source.Ru.Bdu;

public sealed class RuBduDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:ru-bdu";

    public IServiceCollection Register(IServiceCollection services, IConfiguration configuration)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configuration);

        services.AddRuBduConnector(options =>
        {
            configuration.GetSection(ConfigurationSection).Bind(options);
            options.Validate();
        });

        services.AddTransient<RuBduFetchJob>();
        services.AddTransient<RuBduParseJob>();
        services.AddTransient<RuBduMapJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, RuBduJobKinds.Fetch, typeof(RuBduFetchJob));
            EnsureJob(options, RuBduJobKinds.Parse, typeof(RuBduParseJob));
            EnsureJob(options, RuBduJobKinds.Map, typeof(RuBduMapJob));
        });

        return services;
    }

    private static void EnsureJob(JobSchedulerOptions schedulerOptions, string kind, Type jobType)
    {
        if (schedulerOptions.Definitions.ContainsKey(kind))
        {
            return;
        }

        schedulerOptions.Definitions[kind] = new JobDefinition(
            kind,
            jobType,
            schedulerOptions.DefaultTimeout,
            schedulerOptions.DefaultLeaseDuration,
            CronExpression: null,
            Enabled: true);
    }
}
