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

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

/// <summary>
/// Flags booking sessions whose scheduled start passed with no EVV check-in as no-shows. Previously admin-manual
/// (<c>admin_evv/detect_no_shows</c>) — now scheduled on the <c>no_show_scan_cadence_hours</c> cadence; the admin
/// trigger remains an override. Sends <see cref="DetectNoShowSessionsCommand"/> (idempotent — an already-flagged
/// session is not re-flagged).
/// </summary>
internal sealed class NoShowSweepJob(ILogger<NoShowSweepJob> logger) : IRecurringJob
{
    public string Name => "no_show_sweep";

    public async ValueTask<TimeSpan> GetIntervalAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        var config = services.GetRequiredService<IPlatformConfig>();
        var hours = await config.GetConfig<int>("no_show_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 DetectNoShowSessionsCommand(), cancellationToken);

        if (result.IsSuccess && result.Result is { Missed: > 0 } sweep)
            logger.LogInformation("No-show sweep flagged {Missed} missed session(s)", sweep.Missed);
    }
}
