namespace Meezi.Core.Utilities;

/// <summary>Normalizes OTP input (Persian/Arabic digits, whitespace) to 6 ASCII digits.</summary>
public static class OtpNormalizer
{
    public static string Normalize(string? code)
    {
        if (string.IsNullOrWhiteSpace(code))
            return string.Empty;

        Span<char> buffer = stackalloc char[code.Length];
        var n = 0;
        foreach (var ch in code)
        {
            if (ch is >= '0' and <= '9')
                buffer[n++] = ch;
            else
            {
                var d = ch switch
                {
                    >= '\u06F0' and <= '\u06F9' => ch - '\u06F0', // Persian
                    >= '\u0660' and <= '\u0669' => ch - '\u0660', // Arabic-Indic
                    _ => -1
                };
                if (d >= 0)
                    buffer[n++] = (char)('0' + d);
            }
        }

        return n == 0 ? string.Empty : new string(buffer[..n]);
    }

    public static bool IsValidSixDigitCode(string? code)
    {
        var normalized = Normalize(code);
        return normalized.Length == 6 && normalized.All(char.IsDigit);
    }
}
