using AttendanceHub.Sync.Domain;
using AttendanceHub.Sync.Persistence;
using AttendanceHub.Sync.Persistence.Sqlite;
using AttendanceHub.Sync.Upload;
using Xunit;
namespace AttendanceHub.Sync.Tests;
///
/// Ledger retention (PruneLedgerAsync):
/// - acked (Sent + acked_at) punches older than the retention are deleted; unacked rows never are.
/// - client_dlq entries whose punch was later delivered are removed immediately; undelivered stay.
/// - VACUUM runs only when the reclaimed free space meets the threshold.
///
public class LedgerPruneTests : IAsyncLifetime
{
private string _dbPath = null!;
private SQLiteSyncStore _store = null!;
public async Task InitializeAsync()
{
_dbPath = Path.Combine(Path.GetTempPath(), "ahub-ledger-prune", Guid.NewGuid().ToString("N") + ".db");
Directory.CreateDirectory(Path.GetDirectoryName(_dbPath)!);
_store = new SQLiteSyncStore(_dbPath);
await _store.InitializeAsync();
}
public async Task DisposeAsync()
{
await _store.DisposeAsync();
try { Directory.Delete(Path.GetDirectoryName(_dbPath)!, recursive: true); } catch { }
}
private static NormalizedPunch Punch(string pin, DateTimeOffset time, string device = "dev1")
{
var id = new PunchIdentity(device, pin, time);
return new NormalizedPunch(id, PunchSource.Reconciliation, 0, 1, 0, false, 1, "SSR_GetGeneralLogData",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, PunchTimeStatus.Acceptable,
time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
}
private async Task InsertAckedAsync(NormalizedPunch p)
{
await _store.UpsertPunchAsync(p);
var found = await _store.FindPunchAsync(p.Identity);
Assert.NotNull(found);
await _store.ApplyAckAsync(found!.LocalId, RecordOutcome.AcceptedNew, null, "receipt-1",
DateTimeOffset.UtcNow, RetryPolicy.Default);
return found.LocalId;
}
[Fact]
public async Task P01_Acked_Old_Pruned_Recent_And_Unacked_Kept()
{
var old = DateTimeOffset.UtcNow.AddDays(-120);
var recent = DateTimeOffset.UtcNow.AddDays(-5);
var pruned = Punch("1001", old);
await InsertAckedAsync(pruned);
var recentSent = Punch("1002", recent);
await InsertAckedAsync(recentSent);
var oldPending = Punch("1003", old); // never uploaded — must survive any age rule
await _store.UpsertPunchAsync(oldPending);
var r = await _store.PruneLedgerAsync(TimeSpan.FromDays(90), TimeSpan.FromDays(30), long.MaxValue);
Assert.Equal(1, r.PunchesDeleted);
Assert.False(r.Vacuumed); // threshold unreachable
Assert.Null(await _store.FindPunchAsync(pruned.Identity));
Assert.NotNull(await _store.FindPunchAsync(recentSent.Identity));
Assert.NotNull(await _store.FindPunchAsync(oldPending.Identity));
}
[Fact]
public async Task P02_Dlq_Delivered_Removed_Undelivered_Kept()
{
var now = DateTimeOffset.UtcNow;
// Delivered case: DLQ entry whose punch was accepted by the server afterwards.
var p1 = Punch("2001", now.AddDays(-1));
await _store.UpsertPunchAsync(p1);
var id1 = (await _store.FindPunchAsync(p1.Identity))!.LocalId;
await _store.MoveToClientDlqAsync(id1, "Business", "device_not_authorized", now);
await _store.ApplyAckAsync(id1, RecordOutcome.AcceptedNew, null, "receipt-2", now, RetryPolicy.Default);
// Undelivered case: DLQ entry whose punch is still stuck in Dlq state.
var p2 = Punch("2002", now.AddDays(-2));
await _store.UpsertPunchAsync(p2);
var id2 = (await _store.FindPunchAsync(p2.Identity))!.LocalId;
await _store.MoveToClientDlqAsync(id2, "Business", "device_not_authorized", now);
var r1 = await _store.PruneLedgerAsync(TimeSpan.FromDays(90), TimeSpan.FromDays(30), long.MaxValue);
Assert.Equal(1, r1.DlqDeleted); // exactly the delivered one
Assert.NotNull(await _store.FindPunchAsync(p1.Identity)); // recent punches survive
Assert.NotNull(await _store.FindPunchAsync(p2.Identity));
// A second pass removes nothing more: the undelivered entry is recent and not delivered.
var r2 = await _store.PruneLedgerAsync(TimeSpan.FromDays(90), TimeSpan.FromDays(30), long.MaxValue);
Assert.Equal(0, r2.DlqDeleted);
Assert.Equal(0, r2.PunchesDeleted);
}
[Fact]
public async Task P03_Vacuum_Runs_When_Threshold_Met_And_Shrinks_File()
{
var old = DateTimeOffset.UtcNow.AddDays(-100);
var batch = new List();
for (var i = 0; i < 500; i++)
batch.Add(Punch("3" + i.ToString("D4"), old.AddSeconds(i)));
var res = await _store.UpsertBatchAsync(batch);
Assert.Equal(500, res.Inserted);
foreach (var p in batch)
{
var found = await _store.FindPunchAsync(p.Identity);
await _store.ApplyAckAsync(found!.LocalId, RecordOutcome.AcceptedNew, null, "receipt-3",
DateTimeOffset.UtcNow, RetryPolicy.Default);
}
long Size() => new FileInfo(_dbPath).Length
+ (File.Exists(_dbPath + "-wal") ? new FileInfo(_dbPath + "-wal").Length : 0);
var before = Size();
var r = await _store.PruneLedgerAsync(TimeSpan.FromDays(30), TimeSpan.FromDays(30), vacuumThresholdBytes: 0);
Assert.Equal(500, r.PunchesDeleted);
Assert.True(r.Vacuumed);
Assert.True(r.FreelistBytesBefore > 0);
Assert.True(Size() < before, $"db should shrink: before={before} after={Size()}");
Assert.Equal(0, (await _store.GetStatsAsync()).PunchCount);
}
}