using System.Text.RegularExpressions;

namespace Nalu.Web.PostProcessors;

public class NormalizePostalCode : IPostProcessor
{
    public string Name => "normalize_postal_code";

    // Accepts: 3–10 alphanumeric chars, optionally split by a single space or hyphen
    private static readonly Regex ValidPattern =
        new(@"^[A-Z0-9]{2,}([\s\-][A-Z0-9]{2,})?$", RegexOptions.Compiled);

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return ProcessorResult.Invalid("Código postal vazio");

        // Uppercase + collapse whitespace
        var normalized = Regex.Replace(value.Trim().ToUpperInvariant(), @"\s+", " ");

        // Reject all-zeros
        if (Regex.IsMatch(normalized, @"^0+$"))
            return ProcessorResult.Invalid("Código postal inválido (todos zeros)");

        // Must contain at least one digit or letter group matching postal pattern
        if (!ValidPattern.IsMatch(normalized))
            return ProcessorResult.Invalid($"Formato de código postal não reconhecido: {normalized}");

        return ProcessorResult.Ok(normalized);
    }
}
