#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using Baya.Application.Contracts.Configuration;
using Baya.Application.Features.Verification.Commands.ScanExpiringCredentials;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Baya.Infrastructure.Persistence.Services.Scheduling.Jobs;

/// <summary>
/// Scans for lapsed time-limited verification steps (criminal-record especially), reverting each to expired,
/// raising a renewal alert/notification, and re-gating bookability. Previously admin-manual
/// (<c>admin_verifications/scan_expiring</c>) — now scheduled on the <c>verification_expiry_scan_cadence_hours</c>
/// cadence; the admin trigger remains an override. Sends <see cref="ScanExpiringCredentialsCommand"/> (idempotent).
/// </summary>
internal sealed class CredentialExpiryScanJob(ILogger<CredentialExpiryScanJob> logger) : IRecurringJob
{
    public string Name => "verification_expiry_scan";

    public async ValueTask<TimeSpan> GetIntervalAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        var config = services.GetRequiredService<IPlatformConfig>();
        var hours = await config.GetConfig<int>("verification_expiry_scan_cadence_hours", cancellationToken);
        return TimeSpan.FromHours(hours);
    }

    public async ValueTask RunAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        var sender = services.GetRequiredService<ISender>();
        var result = await sender.Send(new ScanExpiringCredentialsCommand(), cancellationToken);

        if (result.IsSuccess && result.Result is { } scan && scan.RevertedNurses > 0)
            logger.LogInformation(
                "Credential-expiry scan reverted {Nurses} nurse(s) across {Steps} expired step(s)",
                scan.RevertedNurses, scan.ScannedSteps);
    }
}
