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

namespace ZB.MOM.NatsNet.Server;

internal static class ConsumerActionExtensions
{
    internal static string String(this ConsumerAction action) =>
        action switch
        {
            ConsumerAction.CreateOrUpdate => "\"create_or_update\"",
            ConsumerAction.Create => "\"create\"",
            ConsumerAction.Update => "\"update\"",
            _ => "\"create_or_update\"",
        };
}

public sealed class ConsumerActionJsonConverter : JsonConverter<ConsumerAction>
{
    public override ConsumerAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.String)
            throw new JsonException("can not unmarshal token");

        return reader.GetString() switch
        {
            "create" => ConsumerAction.Create,
            "update" => ConsumerAction.Update,
            "create_or_update" => ConsumerAction.CreateOrUpdate,
            var value => throw new JsonException($"unknown consumer action: {value}"),
        };
    }

    public override void Write(Utf8JsonWriter writer, ConsumerAction value, JsonSerializerOptions options)
    {
        switch (value)
        {
            case ConsumerAction.Create:
                writer.WriteStringValue("create");
                break;
            case ConsumerAction.Update:
                writer.WriteStringValue("update");
                break;
            case ConsumerAction.CreateOrUpdate:
                writer.WriteStringValue("create_or_update");
                break;
            default:
                throw new JsonException($"can not marshal {value}");
        }
    }
}
