using System.Text.Json;

namespace NATS.Server.Raft;

public sealed class RaftSnapshotStore
{
    private RaftSnapshot? _snapshot;
    private readonly string? _snapshotPath;

    public RaftSnapshotStore(string? snapshotPath = null)
    {
        _snapshotPath = snapshotPath;
    }

    public Task SaveAsync(RaftSnapshot snapshot, CancellationToken ct)
    {
        _snapshot = snapshot;
        if (!string.IsNullOrWhiteSpace(_snapshotPath))
        {
            var dir = Path.GetDirectoryName(_snapshotPath);
            if (!string.IsNullOrWhiteSpace(dir))
                Directory.CreateDirectory(dir);

            File.WriteAllText(_snapshotPath, JsonSerializer.Serialize(snapshot));
        }

        return Task.CompletedTask;
    }

    public Task<RaftSnapshot?> LoadAsync(CancellationToken ct)
    {
        if (_snapshot == null
            && !string.IsNullOrWhiteSpace(_snapshotPath)
            && File.Exists(_snapshotPath))
        {
            _snapshot = JsonSerializer.Deserialize<RaftSnapshot>(File.ReadAllText(_snapshotPath));
        }

        return Task.FromResult(_snapshot);
    }
}
