using EonaCat.LogStack.Core;
using System;

namespace EonaCat.LogStack.Boosters;

/// <summary>
/// Adds a stable fingerprint for exceptions/errors so incidents can be grouped.
/// Useful for alerting systems and production error aggregation.
/// </summary>
public sealed class ExceptionFingerprintBooster : BoosterBase
{
    public ExceptionFingerprintBooster() : base("ExceptionFingerprint") { }

    public override bool Boost(ref LogEventBuilder builder)
    {
        try
        {
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var input = System.Text.Encoding.UTF8.GetBytes(
                    builder.ToString() ?? string.Empty);

                var hash = sha256.ComputeHash(input);

                var hex = BitConverter.ToString(hash)
                    .Replace("-", string.Empty)
                    .Substring(0, 16);

                builder.WithProperty("event_fingerprint", hex);
            }
        }
        catch
        {
            // Do not allow logging failures to break the application
        }

        return true;
    }
}
