// This file is auto-generated by alef — DO NOT EDIT.
// alef:hash:4e15143f4af1ae8bafbdb1506ef057da924484c66a19483966333558ad437e75
// To regenerate: alef generate
// To verify freshness: alef verify --exit-code
// Issues & docs: https://github.com/kreuzberg-dev/alef
#nullable enable

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Kreuzberg;

/// <summary>
/// Converts byte arrays to and from JSON integer arrays.
/// </summary>
/// <remarks>
/// System.Text.Json serializes byte[] as base64 strings by default, but Rust's serde
/// for Vec&lt;u8&gt; expects JSON arrays of integers [72, 101, 108, ...].
/// Apply this converter to byte[] fields that are serialized to FFI with
/// [JsonConverter(typeof(ByteArrayToIntArrayConverter))].
/// </remarks>
public sealed class ByteArrayToIntArrayConverter : JsonConverter<byte[]>
{
    /// <summary>
    /// Reads a JSON array of integers and converts it to a byte array.
    /// </summary>
    public override byte[]? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartArray)
        {
            throw new JsonException("Expected JSON array for byte[]");
        }

        var bytes = new List<byte>();
        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndArray)
            {
                break;
            }
            if (reader.TokenType == JsonTokenType.Number)
            {
                bytes.Add((byte)reader.GetInt32());
            }
            else
            {
                throw new JsonException($"Unexpected token type: {reader.TokenType}");
            }
        }

        return bytes.ToArray();
    }

    /// <summary>
    /// Writes a byte array as a JSON array of integers.
    /// </summary>
    public override void Write(
        Utf8JsonWriter writer,
        byte[] value,
        JsonSerializerOptions options)
    {
        writer.WriteStartArray();
        foreach (var b in value)
        {
            writer.WriteNumberValue(b);
        }
        writer.WriteEndArray();
    }
}
