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

namespace StellaOps.Feedser.Source.Distro.RedHat;

public sealed class RedHatDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:redhat";
    private const string FetchCron = "0,15,30,45 * * * *";
    private const string ParseCron = "5,20,35,50 * * * *";
    private const string MapCron = "10,25,40,55 * * * *";

    private static readonly TimeSpan FetchTimeout = TimeSpan.FromMinutes(12);
    private static readonly TimeSpan ParseTimeout = TimeSpan.FromMinutes(15);
    private static readonly TimeSpan MapTimeout = TimeSpan.FromMinutes(20);
    private static readonly TimeSpan LeaseDuration = TimeSpan.FromMinutes(6);

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

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

        var schedulerBuilder = new JobSchedulerBuilder(services);

        schedulerBuilder
            .AddJob<RedHatFetchJob>(
                RedHatJobKinds.Fetch,
                cronExpression: FetchCron,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<RedHatParseJob>(
                RedHatJobKinds.Parse,
                cronExpression: ParseCron,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<RedHatMapJob>(
                RedHatJobKinds.Map,
                cronExpression: MapCron,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
