using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.DependencyInjection;
using StellaOps.Concelier.Core.Jobs;
using StellaOps.Concelier.Connector.Cccs.Configuration;

namespace StellaOps.Concelier.Connector.Cccs;

public sealed class CccsDependencyInjectionRoutine : IDependencyInjectionRoutine
{
    private const string ConfigurationSection = "concelier:sources:cccs";

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

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

        services.AddTransient<CccsFetchJob>();

        services.PostConfigure<JobSchedulerOptions>(options =>
        {
            EnsureJob(options, CccsJobKinds.Fetch, typeof(CccsFetchJob));
        });

        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);
    }
}
