using System.Text.Json.Serialization;
using OneOf;

namespace AsyncApiRenderer.Data;

public class Message
{
    public string Summary { get; set; } = "";

    public string Description { get; set; } = "";

    public JsonSchemaNode Payload { get; set; }
        = new JsonSchemaNode();

    [JsonPropertyName("x-response")]
    [JsonConverter(typeof(OneOfConverter<JsonSchemaNode, List<JsonSchemaNode>>))]
    public OneOf<JsonSchemaNode, List<JsonSchemaNode>>? Response { get; set; }

    [JsonIgnore]
    public string? Name
    {
        get
        {
            if (Payload.Properties != null
                && Payload.Properties.TryGetValue("$type", out JsonSchemaNode? node)
                && node.Enum != null
                && node.Enum.Count == 1
            )
                return node.Enum[0];
            else return null;
        }
    }

    public IEnumerable<string> GetResponseMessages()
    {
        if (Response is null)
            yield break;
        if (Response.Value.TryPickT0(out var node, out var list))
        {
            if (node.Ref != null)
                yield return TrimMessageName(node.Ref);
        }
        else
        {
            foreach (var item in list)
                if (item.Ref != null)
                    yield return TrimMessageName(item.Ref);
        }
    }

    private string TrimMessageName(string name)
    {
        const string prefix = "#/components/messages/";
        if (name.StartsWith(prefix))
            return name.Substring(prefix.Length);
        else return name;
    }
}
