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

namespace StellaOps.Feedser.Source.Distro.Debian;

public sealed class DebianDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:debian";
    private const string FetchSchedule = "*/30 * * * *";
    private const string ParseSchedule = "7,37 * * * *";
    private const string MapSchedule = "12,42 * * * *";

    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.AddDebianConnector(options =>
        {
            configuration.GetSection(ConfigurationSection).Bind(options);
            options.Validate();
        });

        var scheduler = new JobSchedulerBuilder(services);
        scheduler
            .AddJob<DebianFetchJob>(
                DebianJobKinds.Fetch,
                cronExpression: FetchSchedule,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<DebianParseJob>(
                DebianJobKinds.Parse,
                cronExpression: ParseSchedule,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<DebianMapJob>(
                DebianJobKinds.Map,
                cronExpression: MapSchedule,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
