using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Routing;

namespace Baya.WebFramework.Routing;

public sealed class SnakeCaseParameterTransformer : IOutboundParameterTransformer
{
    private static readonly Regex _upperAfterLower = new(@"([a-z0-9])([A-Z])", RegexOptions.Compiled);
    private static readonly Regex _consecutiveUpper = new(@"([A-Z]+)([A-Z][a-z])", RegexOptions.Compiled);

    public string TransformOutbound(object value)
    {
        if (value is null) return null;
        var s = _consecutiveUpper.Replace(value.ToString()!, "$1_$2");
        return _upperAfterLower.Replace(s, "$1_$2").ToLowerInvariant();
    }
}
