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

namespace StellaOps.Feedser.Source.Ics.Cisa;

public sealed class IcsCisaDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:ics-cisa";

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

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

        services.AddTransient<IcsCisaFetchJob>();
        services.AddTransient<IcsCisaParseJob>();
        services.AddTransient<IcsCisaMapJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, IcsCisaJobKinds.Fetch, typeof(IcsCisaFetchJob));
            EnsureJob(options, IcsCisaJobKinds.Parse, typeof(IcsCisaParseJob));
            EnsureJob(options, IcsCisaJobKinds.Map, typeof(IcsCisaMapJob));
        });

        return services;
    }

    private static void EnsureJob(JobSchedulerOptions options, string kind, Type jobType)
    {
        ArgumentNullException.ThrowIfNull(options);

        if (options.Definitions.ContainsKey(kind))
        {
            return;
        }

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