using System;
using System.Collections.Generic;

namespace ZB.MOM.WW.MxGateway.Worker.Bootstrap;

/// <summary>
/// Redacts sensitive fields from worker log messages.
/// </summary>
public static class WorkerLogRedactor
{
    /// <summary>
    /// Replacement text for redacted values.
    /// </summary>
    public const string RedactedValue = "[redacted]";

    private static readonly string[] SensitiveFieldNameParts =
    [
        "nonce",
        "secret",
        "password",
        "token",
        "credential",
        "apikey",
        "api_key",
    ];

    /// <summary>
    /// Redacts sensitive field values from a log field dictionary.
    /// </summary>
    /// <param name="fields">Dictionary of field names and values.</param>
    /// <returns>A new dictionary with sensitive field values replaced by <see cref="RedactedValue"/>.</returns>
    public static Dictionary<string, object?> RedactFields(IReadOnlyDictionary<string, object?> fields)
    {
        Dictionary<string, object?> redactedFields = [];

        foreach (KeyValuePair<string, object?> field in fields)
        {
            redactedFields[field.Key] = RedactValue(field.Key, field.Value);
        }

        return redactedFields;
    }

    /// <summary>
    /// Redacts a single value if its field name contains sensitive keywords.
    /// </summary>
    /// <param name="fieldName">Name of the field to check.</param>
    /// <param name="value">Value to redact if sensitive.</param>
    /// <returns>The redacted placeholder when <paramref name="fieldName"/> looks sensitive; otherwise the original value.</returns>
    public static object? RedactValue(string fieldName, object? value)
    {
        if (value is null)
        {
            return null;
        }

        foreach (string sensitiveFieldNamePart in SensitiveFieldNameParts)
        {
            if (fieldName.IndexOf(sensitiveFieldNamePart, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                return RedactedValue;
            }
        }

        return value;
    }
}
