using System.Text.Json.Nodes;

namespace Nalu.Web.PostProcessors;

/// Reads the cancel-intent JSON and sets SuggestionKeyOverride based on cancel_type + is_threat.
public class SelectCancelSuggestion : IPostProcessor
{
    public string Name => "select_cancel_suggestion";

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

        try
        {
            var obj = JsonNode.Parse(value)?.AsObject();
            if (obj is null) return ProcessorResult.Ok(value);

            var cancelType = obj["cancel_type"]?.GetValue<string>() ?? "none";
            var isThreat   = obj["is_threat"]?.GetValue<bool>() ?? false;

            var key = cancelType switch
            {
                "service"   => isThreat ? "when_threat" : "when_cancel_service",
                "operation" => "when_cancel_operation",
                _           => "when_not_cancel"
            };

            return ProcessorResult.WithOverride(value, key);
        }
        catch
        {
            return ProcessorResult.Ok(value);
        }
    }
}
