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

namespace YandexMusic.API.Models.Radio.Restriction;

/// <summary>Конвертер для ограничений радиостанции (дискретная шкала или перечисление).</summary>
public class YRestrictionConverter : JsonConverter<YRestriction>
{
    public override YRestriction? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
            throw new JsonException("Ожидается объект ограничения");

        using var doc = JsonDocument.ParseValue(ref reader);
        var root = doc.RootElement;

        var typeProp = root.GetProperty("type");
        var typeStr = typeProp.GetString();
        if (!Enum.TryParse<YRestrictionType>(typeStr, true, out var restrictionType))
            throw new JsonException($"Неизвестный тип ограничения: {typeStr}");

        var rawText = root.GetRawText();

        return restrictionType switch
        {
            YRestrictionType.Enum => JsonSerializer.Deserialize<YRestrictionEnum>(rawText, options),
            YRestrictionType.DiscreteScale => JsonSerializer.Deserialize<YRestrictionDiscreteScale>(rawText, options),
            _ => JsonSerializer.Deserialize<YRestriction>(rawText, options)
        };
    }

    public override void Write(Utf8JsonWriter writer, YRestriction value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, options);
    }
}