using FASTER.core;

namespace PayForReactions;

public class NostrStore : IDisposable
{
    private readonly ILogger<NostrStore> _logger;
    private readonly CancellationTokenSource _cts = new();
    private readonly FasterKVSettings<byte[], byte[]> _storeSettings;
    private readonly FasterKV<byte[], byte[]> _store;

    private readonly Task _checkPointer;

    public NostrStore(string dir, ILogger<NostrStore> logger)
    {
        _logger = logger;
        _storeSettings = new FasterKVSettings<byte[], byte[]>(Path.Combine(dir, "main"), false, _logger);
        _store = new(_storeSettings);
        var version = _store.GetLatestCheckpointVersion();
        if (version != -1)
        {
            _store.Recover();
        }

        _checkPointer = Task.Factory.StartNew(async () =>
        {
            while (!_cts.IsCancellationRequested)
            {
                await Task.Delay(10_000);
                await _store.TakeHybridLogCheckpointAsync(CheckpointType.Snapshot, true);
            }
        });
    }
    public FasterKV<byte[], byte[]> MainStore => _store;

    public void Dispose()
    {
        _cts.Cancel();
        _checkPointer.ConfigureAwait(false).GetAwaiter().GetResult();

        _store.Dispose();
        _storeSettings.Dispose();
    }
}
