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

namespace StellaOps.Feedser.Source.Vndr.Apple;

public sealed class AppleDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "feedser:sources:apple";

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

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

        services.AddTransient<AppleFetchJob>();
        services.AddTransient<AppleParseJob>();
        services.AddTransient<AppleMapJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, AppleJobKinds.Fetch, typeof(AppleFetchJob));
            EnsureJob(options, AppleJobKinds.Parse, typeof(AppleParseJob));
            EnsureJob(options, AppleJobKinds.Map, typeof(AppleMapJob));
        });

        return services;
    }

    private static void EnsureJob(JobSchedulerOptions options, string kind, Type jobType)
    {
        if (options.Definitions.ContainsKey(kind))
        {
            return;
        }

        options.Definitions[kind] = new JobDefinition(
            kind,
            jobType,
            options.DefaultTimeout,
            options.DefaultLeaseDuration,
            CronExpression: null,
            Enabled: true);
    }
}
