using System.Text.Json;
using System.Text.Json.Nodes;

namespace Nalu.Web.PostProcessors;

/// Reads the JSON produced by ParseDate, adds "age" and "minor" fields.
/// Sets SuggestionKeyOverride = "when_minor" when age < 18.
public class CalculateAge : IPostProcessor
{
    public string Name => "calculate_age";

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return ProcessorResult.Invalid("Nenhuma data para calcular a idade");

        JsonObject obj;
        try
        {
            obj = JsonNode.Parse(value)?.AsObject()
                  ?? throw new InvalidOperationException();
        }
        catch
        {
            return ProcessorResult.Invalid("Formato interno de data inválido");
        }

        if (!DateTime.TryParse(obj["date"]?.GetValue<string>(), out var birth))
            return ProcessorResult.Invalid("Campo 'date' ausente ou inválido no JSON de data");

        var age = ParseDate.ComputeAge(birth);
        var minor = age < 18;

        obj["age"] = age;
        obj["minor"] = minor;

        var json = obj.ToJsonString();

        return minor
            ? ProcessorResult.WithOverride(json, "when_minor")
            : ProcessorResult.Ok(json);
    }
}
