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

namespace StellaOps.Feedser.Source.Distro.Ubuntu;

public sealed class UbuntuDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:ubuntu";
    private const string FetchCron = "*/20 * * * *";
    private const string ParseCron = "7,27,47 * * * *";
    private const string MapCron = "10,30,50 * * * *";

    private static readonly TimeSpan FetchTimeout = TimeSpan.FromMinutes(4);
    private static readonly TimeSpan ParseTimeout = TimeSpan.FromMinutes(5);
    private static readonly TimeSpan MapTimeout = TimeSpan.FromMinutes(8);
    private static readonly TimeSpan LeaseDuration = TimeSpan.FromMinutes(3);

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

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

        var scheduler = new JobSchedulerBuilder(services);
        scheduler
            .AddJob<UbuntuFetchJob>(
                UbuntuJobKinds.Fetch,
                cronExpression: FetchCron,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<UbuntuParseJob>(
                UbuntuJobKinds.Parse,
                cronExpression: ParseCron,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<UbuntuMapJob>(
                UbuntuJobKinds.Map,
                cronExpression: MapCron,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
