using System.Net.Mail;

namespace Ikar.Server.Infrastructure.Auth;

public static class EmailAddressNormalizer
{
    private static readonly HashSet<string> AllowedRegistrationDomains = new(StringComparer.OrdinalIgnoreCase)
    {
        "YANDEX.RU",
        "MAIL.RU"
    };

    public const string UnsupportedRegistrationDomainMessage =
        "Регистрация доступна только через почту yandex.ru или mail.ru.";

    public static string? Normalize(string? email)
    {
        var trimmed = email?.Trim();
        if (string.IsNullOrWhiteSpace(trimmed))
        {
            return null;
        }

        try
        {
            var address = new MailAddress(trimmed);
            return string.Equals(address.Address, trimmed, StringComparison.OrdinalIgnoreCase)
                ? address.Address.ToUpperInvariant()
                : null;
        }
        catch (FormatException)
        {
            return null;
        }
    }

    public static bool IsAllowedRegistrationDomain(string normalizedEmail)
    {
        var atIndex = normalizedEmail.LastIndexOf('@');
        if (atIndex < 0 || atIndex == normalizedEmail.Length - 1)
        {
            return false;
        }

        var domain = normalizedEmail[(atIndex + 1)..];
        return AllowedRegistrationDomains.Contains(domain);
    }
}
