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

namespace StellaOps.Feedser.Source.Distro.Suse;

public sealed class SuseDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:suse";
    private const string FetchCron = "*/30 * * * *";
    private const string ParseCron = "5,35 * * * *";
    private const string MapCron = "10,40 * * * *";

    private static readonly TimeSpan FetchTimeout = TimeSpan.FromMinutes(6);
    private static readonly TimeSpan ParseTimeout = TimeSpan.FromMinutes(10);
    private static readonly TimeSpan MapTimeout = TimeSpan.FromMinutes(10);
    private static readonly TimeSpan LeaseDuration = TimeSpan.FromMinutes(5);

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

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

        var scheduler = new JobSchedulerBuilder(services);
        scheduler
            .AddJob<SuseFetchJob>(
                SuseJobKinds.Fetch,
                cronExpression: FetchCron,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<SuseParseJob>(
                SuseJobKinds.Parse,
                cronExpression: ParseCron,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<SuseMapJob>(
                SuseJobKinds.Map,
                cronExpression: MapCron,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
