using System.Text.Json.Serialization;

namespace NATS.Server.Monitoring;

public sealed class JszHandler
{
    private readonly NatsServer _server;
    private readonly NatsOptions _options;

    public JszHandler(NatsServer server, NatsOptions options)
    {
        _server = server;
        _options = options;
    }

    public JszResponse Build()
    {
        return new JszResponse
        {
            ServerId = _server.ServerId,
            Now = DateTime.UtcNow,
            Enabled = _server.Stats.JetStreamEnabled,
            Memory = 0,
            Storage = 0,
            Streams = _server.JetStreamStreams,
            Consumers = _server.JetStreamConsumers,
            ApiTotal = (ulong)Math.Max(Interlocked.Read(ref _server.Stats.JetStreamApiTotal), 0),
            ApiErrors = (ulong)Math.Max(Interlocked.Read(ref _server.Stats.JetStreamApiErrors), 0),
            Config = new JetStreamConfig
            {
                MaxMemory = _options.JetStream?.MaxMemoryStore ?? 0,
                MaxStorage = _options.JetStream?.MaxFileStore ?? 0,
                StoreDir = _options.JetStream?.StoreDir ?? string.Empty,
            },
        };
    }
}

public sealed class JszResponse
{
    [JsonPropertyName("server_id")]
    public string ServerId { get; set; } = string.Empty;

    [JsonPropertyName("now")]
    public DateTime Now { get; set; }

    [JsonPropertyName("enabled")]
    public bool Enabled { get; set; }

    [JsonPropertyName("memory")]
    public ulong Memory { get; set; }

    [JsonPropertyName("storage")]
    public ulong Storage { get; set; }

    [JsonPropertyName("streams")]
    public int Streams { get; set; }

    [JsonPropertyName("consumers")]
    public int Consumers { get; set; }

    [JsonPropertyName("api_total")]
    public ulong ApiTotal { get; set; }

    [JsonPropertyName("api_errors")]
    public ulong ApiErrors { get; set; }

    [JsonPropertyName("config")]
    public JetStreamConfig Config { get; set; } = new();
}
