using NATS.Server.Auth;

namespace NATS.Server.Monitoring;

public sealed class AccountzHandler
{
    private readonly NatsServer _server;

    public AccountzHandler(NatsServer server)
    {
        _server = server;
    }

    public object Build()
    {
        var accounts = _server.GetAccounts().Select(ToAccountDto).ToArray();
        return new
        {
            accounts,
            num_accounts = accounts.Length,
        };
    }

    public object BuildStats()
    {
        var accounts = _server.GetAccounts().ToArray();
        return new
        {
            total_accounts = accounts.Length,
            total_connections = accounts.Sum(a => a.ClientCount),
            total_subscriptions = accounts.Sum(a => a.SubscriptionCount),
        };
    }

    private static object ToAccountDto(Account account)
    {
        return new
        {
            name = account.Name,
            connections = account.ClientCount,
            subscriptions = account.SubscriptionCount,
            in_msgs = account.InMsgs,
            out_msgs = account.OutMsgs,
        };
    }
}
