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

namespace YandexMusic.API.Models.Common.Cover;

public class YCoverConverter : JsonConverter<YCover>
{
    public override YCover? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject) return null;
        using var doc = JsonDocument.ParseValue(ref reader);
        var root = doc.RootElement;
        var type = root.TryGetProperty("type", out var t) ? t.GetString() : null;
        if (root.TryGetProperty("error", out _)) type = "error";

        return type switch
        {
            "color" => JsonSerializer.Deserialize<YCoverColor>(root.GetRawText(), options),
            "error" => JsonSerializer.Deserialize<YCoverError>(root.GetRawText(), options),
            "from-artist-photos" or "from-album-cover" => JsonSerializer.Deserialize<YCoverImage>(root.GetRawText(), options),
            "pic" => JsonSerializer.Deserialize<YCoverPic>(root.GetRawText(), options),
            "mosaic" => JsonSerializer.Deserialize<YCoverMosaic>(root.GetRawText(), options),
            _ => JsonSerializer.Deserialize<YCover>(root.GetRawText(), options)
        };
    }

    public override void Write(Utf8JsonWriter writer, YCover value, JsonSerializerOptions options)
        => JsonSerializer.Serialize(writer, value, options);
}

[JsonConverter(typeof(YCoverConverter))]
public class YCover
{
    public YCoverType Type { get; set; }
}