using ClaudeDo.Data.Models;
using ClaudeDo.Worker.Logging;

namespace ClaudeDo.Worker.Tests.Logging;

public class LogRingBufferTests
{
    private static readonly DateTime Now = new(2026, 6, 23, 8, 0, 0, DateTimeKind.Utc);

    private static WorkerLogRecord Rec(DateTime ts, string msg = "m", WorkerLogLevel lvl = WorkerLogLevel.Info)
        => new(msg, lvl, ts);

    [Fact]
    public void Evicts_records_older_than_window_on_append()
    {
        var buf = new LogRingBuffer(TimeSpan.FromMinutes(30), utcNow: () => Now);
        buf.Append(Rec(Now.AddMinutes(-40), "old"));
        buf.Append(Rec(Now.AddMinutes(-10), "recent"));

        var snap = buf.Snapshot();

        Assert.Single(snap);
        Assert.Equal("recent", snap[0].Message);
    }

    [Fact]
    public void Evicts_oldest_beyond_cap()
    {
        var buf = new LogRingBuffer(TimeSpan.FromHours(1), cap: 3, utcNow: () => Now);
        for (var i = 0; i < 5; i++) buf.Append(Rec(Now, $"m{i}"));

        var snap = buf.Snapshot();

        Assert.Equal(3, snap.Count);
        Assert.Equal(new[] { "m2", "m3", "m4" }, snap.Select(r => r.Message));
    }

    [Fact]
    public void Snapshot_is_oldest_first()
    {
        var buf = new LogRingBuffer(TimeSpan.FromHours(1), utcNow: () => Now);
        buf.Append(Rec(Now.AddMinutes(-3), "a"));
        buf.Append(Rec(Now.AddMinutes(-2), "b"));
        buf.Append(Rec(Now.AddMinutes(-1), "c"));

        Assert.Equal(new[] { "a", "b", "c" }, buf.Snapshot().Select(r => r.Message));
    }
}
