using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.DependencyInjection;
using StellaOps.Feedser.Core.Jobs;
using StellaOps.Feedser.Source.CertIn.Configuration;

namespace StellaOps.Feedser.Source.CertIn;

public sealed class CertInDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:cert-in";

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

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

        services.AddTransient<CertInFetchJob>();
        services.AddTransient<CertInParseJob>();
        services.AddTransient<CertInMapJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, CertInJobKinds.Fetch, typeof(CertInFetchJob));
            EnsureJob(options, CertInJobKinds.Parse, typeof(CertInParseJob));
            EnsureJob(options, CertInJobKinds.Map, typeof(CertInMapJob));
        });

        return services;
    }

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

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