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

namespace JSMR.Infrastructure.Integrations.DLSite.Serialization;

public sealed class DictionaryConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>> where TKey : notnull
{
    public override Dictionary<TKey, TValue>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null)
            return null;

        if (reader.TokenType == JsonTokenType.StartArray)
        {
            if (!reader.Read())
                throw new JsonException("Unexpected end while reading array.");

            if (reader.TokenType != JsonTokenType.EndArray)
                throw new JsonException("Non-empty JSON array cannot be converted to Dictionary.");

            return [];
        }

        if (reader.TokenType == JsonTokenType.StartObject)
        {
            return JsonSerializer.Deserialize<Dictionary<TKey, TValue>>(ref reader, options) ?? [];
        }

        throw new JsonException($"Unexpected token {reader.TokenType} when reading Dictionary.");
    }

    public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, (IDictionary<TKey, TValue>)value, options);
    }
}