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

namespace StellaOps.Feedser.Source.Vndr.Vmware;

public sealed class VmwareDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:vmware";
    private const string FetchCron = "10,40 * * * *";
    private const string ParseCron = "15,45 * * * *";
    private const string MapCron = "20,50 * * * *";

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

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

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

        var scheduler = new JobSchedulerBuilder(services);
        scheduler
            .AddJob<VmwareFetchJob>(
                VmwareJobKinds.Fetch,
                cronExpression: FetchCron,
                timeout: FetchTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<VmwareParseJob>(
                VmwareJobKinds.Parse,
                cronExpression: ParseCron,
                timeout: ParseTimeout,
                leaseDuration: LeaseDuration)
            .AddJob<VmwareMapJob>(
                VmwareJobKinds.Map,
                cronExpression: MapCron,
                timeout: MapTimeout,
                leaseDuration: LeaseDuration);

        return services;
    }
}
