using System.Collections.Concurrent;
using ClawdDotNet.Core.Audit;

namespace ClawdDotNet.Core.Tests.Infrastructure;

/// <summary>
/// In-Memory-Attrappe des Audit-Logs für Engine-Tests — hält Einträge und Belege in
/// Listen, damit ein Test prüfen kann, was die Engine stempelt, ohne eine Datei.
/// </summary>
internal sealed class InMemoryAuditRepository : IAuditRepository
{
    public ConcurrentQueue<AuditEntry> Entries { get; } = new();
    public ConcurrentQueue<RunReceipt> Receipts { get; } = new();

    public Task AppendAsync(AuditEntry entry, CancellationToken ct)
    {
        Entries.Enqueue(entry);
        return Task.CompletedTask;
    }

    public Task RecordReceiptAsync(RunReceipt receipt, CancellationToken ct)
    {
        Receipts.Enqueue(receipt);
        return Task.CompletedTask;
    }

    public Task<IReadOnlyList<AuditEntry>> ListRecentAsync(int limit, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<AuditEntry>>(Entries.Reverse().Take(limit).ToList());

    public Task<IReadOnlyList<AuditEntry>> ListForRunAsync(string runId, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<AuditEntry>>(Entries.Where(e => e.RunId == runId).ToList());

    public Task<RunReceipt?> GetReceiptForRunAsync(string runId, CancellationToken ct)
        => Task.FromResult(Receipts.LastOrDefault(r => r.RunId == runId));

    public Task<IReadOnlyList<RunReceipt>> ListReceiptsForTaskAsync(string taskId, CancellationToken ct)
        => Task.FromResult<IReadOnlyList<RunReceipt>>(Receipts.Where(r => r.TaskId == taskId).ToList());

    public Task<int> CountAsync(CancellationToken ct) => Task.FromResult(Entries.Count);
}
