using System.Text.RegularExpressions;
using Npgsql;

namespace GmRelay.Bot.Infrastructure.Logging;

public static partial class SecretRedactor
{
    public static string RedactConnectionString(string? connectionString)
    {
        if (string.IsNullOrWhiteSpace(connectionString))
        {
            return string.Empty;
        }

        try
        {
            var builder = new NpgsqlConnectionStringBuilder(connectionString);
            if (!string.IsNullOrWhiteSpace(builder.Password))
            {
                builder.Password = "***";
            }

            return builder.ToString();
        }
        catch (ArgumentException)
        {
            return RedactText(connectionString);
        }
    }

    public static string RedactText(string? text)
    {
        if (string.IsNullOrWhiteSpace(text))
        {
            return string.Empty;
        }

        return SecretKeyValueRegex().Replace(
            text,
            static match => $"{match.Groups["key"].Value}={GetRedactedValue()}");
    }

    private static string GetRedactedValue() => "***";

    [GeneratedRegex(@"(?<key>password|pwd|passwd|token|secret|api[-_]?key)\s*=\s*(?<value>[^;\s,]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
    private static partial Regex SecretKeyValueRegex();
}
