using EonaCat.LogStack.Core;
using System;
using System.Collections.Generic;

namespace EonaCat.LogStack.Boosters;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

/// <summary>
/// Adds custom properties from a callback
/// </summary>
public sealed class CallbackBooster : BoosterBase
{
    private readonly Func<Dictionary<string, object?>> _propertiesCallback;

    public CallbackBooster(string name, Func<Dictionary<string, object?>> propertiesCallback) : base(name)
    {
        _propertiesCallback = propertiesCallback ?? throw new ArgumentNullException(nameof(propertiesCallback));
    }

    public override bool Boost(ref LogEventBuilder builder)
    {
        try
        {
            var properties = _propertiesCallback();
            if (properties != null)
            {
                foreach (var kvp in properties)
                {
                    builder.WithProperty(kvp.Key, kvp.Value);
                }
            }
        }
        catch
        {
            // Swallow exceptions in boosters to prevent logging failures
        }
        return true;
    }
}
