using System.Text.Json;
using System.Text.RegularExpressions;

namespace Nalu.Web.PostProcessors;

/// Normalizes Brazilian vehicle plates (Mercosul and old format).
/// Returns JSON: {"plate":"ABC1D23","format":"mercosul"} or {"plate":"ABC1234","format":"old"}.
public class FormatPlate : IPostProcessor
{
    public string Name => "format_plate";

    // Mercosul: AAA1B23
    private static readonly Regex Mercosul = new(@"^([A-Z]{3})(\d)([A-Z])(\d{2})$", RegexOptions.Compiled);
    // Old: AAA1234
    private static readonly Regex Old = new(@"^([A-Z]{3})(\d{4})$", RegexOptions.Compiled);

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return ProcessorResult.Invalid("Placa não informada");

        // Normalize: uppercase, strip non-alphanumeric
        var normalized = Regex.Replace(value.ToUpperInvariant(), @"[^A-Z0-9]", "");

        if (Mercosul.IsMatch(normalized))
        {
            var json = JsonSerializer.Serialize(new { plate = normalized, format = "mercosul" });
            return ProcessorResult.Ok(json);
        }

        if (Old.IsMatch(normalized))
        {
            var json = JsonSerializer.Serialize(new { plate = normalized, format = "old" });
            return ProcessorResult.Ok(json);
        }

        return ProcessorResult.Invalid($"Placa inválida: '{normalized}'. Use ABC1D23 (Mercosul) ou ABC1234 (antiga).");
    }
}
