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

namespace StellaOps.Feedser.Source.Osv;

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

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

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

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

        var scheduler = new JobSchedulerBuilder(services);
        scheduler
            .AddJob<OsvFetchJob>(
                OsvJobKinds.Fetch,
                cronExpression: FetchCron,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<OsvParseJob>(
                OsvJobKinds.Parse,
                cronExpression: ParseCron,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<OsvMapJob>(
                OsvJobKinds.Map,
                cronExpression: MapCron,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
