using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Persistence.Sqlite;
using Microsoft.Extensions.Logging;
namespace AttendanceHub.Sync.Host;
///
/// Daily ledger hygiene for the local SQLite outbox:
/// 1) removes client-DLQ entries whose punch was later delivered (or outlived their retention),
/// 2) prunes acked punches (upload_state='Sent' + acked_at) older than the punch retention,
/// 3) VACUUMs when enough free pages were reclaimed.
/// Store-only maintenance — independent of acquisition and delivery; failures are contained.
/// First pass runs shortly after start (deploy-time cleanup), then once every 24h.
///
public sealed class LedgerMaintenance
{
/// Keep the same 90-day horizon as the operational reporting window (shared with ingest).
public const int PunchRetentionDays = RetentionPolicy.PunchRetentionDays;
/// Undelivered DLQ entries older than this are dropped (delivered ones go immediately).
public const int DlqRetentionDays = 30;
/// Only pay for VACUUM when at least this much free space can be reclaimed.
public const long VacuumThresholdBytes = 4L * 1024 * 1024;
private static readonly TimeSpan InitialDelay = TimeSpan.FromSeconds(90);
private static readonly TimeSpan Cycle = TimeSpan.FromHours(24);
private readonly SQLiteSyncStore _store;
private readonly ILogger _log;
public LedgerMaintenance(SQLiteSyncStore store, ILogger log)
{
_store = store;
_log = log;
}
public async Task RunAsync(CancellationToken cancellationToken)
{
try
{
await Task.Delay(InitialDelay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
while (!cancellationToken.IsCancellationRequested)
{
try
{
var r = await _store.PruneLedgerAsync(
RetentionPolicy.PunchRetention,
TimeSpan.FromDays(DlqRetentionDays),
VacuumThresholdBytes,
cancellationToken).ConfigureAwait(false);
if (r.PunchesDeleted == 0 && r.DlqDeleted == 0)
_log.LogInformation("LEDGER_PRUNE nothing_to_prune db_mb={M1:F1}", r.DbBytesAfter / (1024.0 * 1024.0));
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_log.LogError(ex, "LEDGER_PRUNE_FAIL (next pass in 24h)");
}
try
{
await Task.Delay(Cycle, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
_log.LogInformation("LEDGER_MAINTENANCE_STOP");
}
}