namespace Nalu.Web.PostProcessors;

public class CorrectEmailTypos : IPostProcessor
{
    public string Name => "correct_email_typos";

    private static readonly Dictionary<string, string> DomainFixes = new(StringComparer.OrdinalIgnoreCase)
    {
        // Gmail
        { "gmail.com.br", "gmail.com" },
        { "gamil.com",    "gmail.com" },
        { "gmaill.com",   "gmail.com" },
        { "gnail.com",    "gmail.com" },
        { "gmail.con",    "gmail.com" },
        { "gmal.com",     "gmail.com" },
        // Hotmail
        { "hotmal.com",   "hotmail.com" },
        { "hotmial.com",  "hotmail.com" },
        { "hotmail.con",  "hotmail.com" },
        { "homail.com",   "hotmail.com" },
        { "htmail.com",   "hotmail.com" },
        // Outlook
        { "outlok.com",   "outlook.com" },
        { "outllok.com",  "outlook.com" },
        { "outlook.con",  "outlook.com" },
        // Yahoo
        { "yaho.com",     "yahoo.com" },
        { "yahooo.com",   "yahoo.com" },
        { "yahoo.con",    "yahoo.com" },
        // iCloud
        { "iclod.com",    "icloud.com" },
        { "icould.com",   "icloud.com" },
        // UOL/BOL
        { "bol.com.be",   "bol.com.br" },
        { "uol.com.be",   "uol.com.br" },
    };

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return ProcessorResult.Ok(value);

        var email = value.Trim().ToLowerInvariant();
        var atIdx = email.IndexOf('@');
        if (atIdx < 0) return ProcessorResult.Ok(email);

        var local = email[..atIdx];
        var domain = email[(atIdx + 1)..];

        if (DomainFixes.TryGetValue(domain, out var corrected))
        {
            var fixedEmail = $"{local}@{corrected}";
            return ProcessorResult.Corrected(fixedEmail, value.Trim());
        }

        return ProcessorResult.Ok(email);
    }
}
