using System.Text;

namespace Argus.Infrastructure;

public static class IdentifierUtility
{
    public static string Normalize(string? value, string fallback)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return fallback;
        }

        var builder = new StringBuilder(value.Length);
        var lastWasSeparator = false;

        foreach (var character in value.Trim().ToLowerInvariant())
        {
            if (char.IsLetterOrDigit(character))
            {
                builder.Append(character);
                lastWasSeparator = false;
                continue;
            }

            if (character is '-' or '_' or '.')
            {
                if (!lastWasSeparator)
                {
                    builder.Append(character);
                    lastWasSeparator = true;
                }
            }
        }

        var normalized = builder.ToString().Trim('-', '_', '.');
        return string.IsNullOrWhiteSpace(normalized) ? fallback : normalized;
    }
}
