using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;

namespace SIGCM2.Infrastructure.Audit.Jobs;

/// UDT-010 (#REQ-AUD-6) — DI extension to register Quartz + the 3 audit maintenance jobs.
/// Call from Program.cs: builder.Services.AddAuditMaintenance(builder.Configuration).
public static class AuditMaintenanceRegistration
{
    public static IServiceCollection AddAuditMaintenance(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddQuartz(q =>
        {
            var partitionKey = new JobKey(nameof(AuditPartitionManagerJob));
            q.AddJob<AuditPartitionManagerJob>(j => j.WithIdentity(partitionKey));
            q.AddTrigger(t => t
                .ForJob(partitionKey)
                .WithIdentity($"{nameof(AuditPartitionManagerJob)}-trigger")
                .WithCronSchedule(AuditPartitionManagerJob.CronSchedule, x => x.InTimeZone(TimeZoneInfo.Utc)));

            var retentionKey = new JobKey(nameof(AuditRetentionEnforcerJob));
            q.AddJob<AuditRetentionEnforcerJob>(j => j.WithIdentity(retentionKey));
            q.AddTrigger(t => t
                .ForJob(retentionKey)
                .WithIdentity($"{nameof(AuditRetentionEnforcerJob)}-trigger")
                .WithCronSchedule(AuditRetentionEnforcerJob.CronSchedule, x => x.InTimeZone(TimeZoneInfo.Utc)));

            var integrityKey = new JobKey(nameof(AuditIntegrityCheckJob));
            q.AddJob<AuditIntegrityCheckJob>(j => j.WithIdentity(integrityKey));
            q.AddTrigger(t => t
                .ForJob(integrityKey)
                .WithIdentity($"{nameof(AuditIntegrityCheckJob)}-trigger")
                .WithCronSchedule(AuditIntegrityCheckJob.CronSchedule, x => x.InTimeZone(TimeZoneInfo.Utc)));
        });

        services.AddQuartzHostedService(opts => opts.WaitForJobsToComplete = true);

        return services;
    }
}
