#nullable enable
using System.Text.RegularExpressions;
using Baya.SharedKernel.Extensions;

namespace Baya.Application.Features.Identity;

/// <summary>
/// Normalizes an Iranian mobile number to the canonical <c>09xxxxxxxxx</c> form (Persian digits
/// translated, +98/0098/98 prefixes folded). The canonical form is what gets stored, hashed, and
/// rate-limit-keyed — one identity per phone requires one spelling per phone.
/// </summary>
internal static partial class IranianPhone
{
    [GeneratedRegex(@"^(?:\+98|0098|98|0)?(9\d{9})$")]
    private static partial Regex MobilePattern();

    public static string? Normalize(string? raw)
    {
        if (string.IsNullOrWhiteSpace(raw))
            return null;

        var digits = raw.Trim().Fa2En().Replace(" ", string.Empty).Replace("-", string.Empty);

        var match = MobilePattern().Match(digits);
        return match.Success ? $"0{match.Groups[1].Value}" : null;
    }

    public static bool IsValid(string? raw) => Normalize(raw) is not null;
}