using CareFix.Api.Hospitals;
using CareFix.Api.Options;
using Dapper;
using Microsoft.Extensions.Options;
namespace CareFix.Api.Infrastructure;
///
/// Nightly housekeeping: enforces the retention periods promised in the hospital addendum and
/// recaptures schema snapshots that have gone stale (usually after a HIS upgrade).
/// Runs once a day at the configured UTC hour; safe to run more than once.
///
public sealed class MaintenanceWorker(
ControlDb db, HospitalAdminService hospitals, AuditService audit,
IOptions options, ILogger log) : BackgroundService
{
private DateOnly _lastRun = DateOnly.MinValue;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Give the service a minute to finish starting before any heavy work.
try { await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } catch (OperationCanceledException) { return; }
while (!stoppingToken.IsCancellationRequested)
{
var now = DateTime.UtcNow;
var today = DateOnly.FromDateTime(now);
if (now.Hour == Math.Clamp(options.Value.Maintenance.HourUtc, 0, 23) && _lastRun != today)
{
_lastRun = today;
try { await RunAsync(stoppingToken); }
catch (Exception ex) when (ex is not OperationCanceledException) { log.LogError(ex, "Nightly maintenance failed"); }
}
try { await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken); } catch (OperationCanceledException) { return; }
}
}
/// Also callable on demand from the admin API.
public async Task