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

namespace StellaOps.Feedser.Source.Vndr.Cisco;

public sealed class CiscoDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:cisco";

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

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

        services.AddTransient<CiscoFetchJob>();
        services.AddTransient<CiscoParseJob>();
        services.AddTransient<CiscoMapJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, CiscoJobKinds.Fetch, typeof(CiscoFetchJob));
            EnsureJob(options, CiscoJobKinds.Parse, typeof(CiscoParseJob));
            EnsureJob(options, CiscoJobKinds.Map, typeof(CiscoMapJob));
        });

        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);
    }
}
