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


namespace OnlineSalesAutoCrop.CoreAPI.Converter;

public class NullableDecimalConverter : JsonConverter<decimal?>
{
    public override decimal? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null)
            return null;

        if (reader.TokenType == JsonTokenType.Number)
        {
            var value = reader.GetInt32();
            return value == 0 ? null : value;
        }

        if (reader.TokenType == JsonTokenType.String)
        {
            var value = reader.GetString();

            if (string.IsNullOrWhiteSpace(value) || value == "0")
                return null;

            if (int.TryParse(value, out var result))
                return result;

            throw new JsonException($"Invalid ScaleValue: {value}");
        }

        throw new JsonException("ScaleValue must be a number, string, or null.");
    }

    public override void Write(
        Utf8JsonWriter writer,
        decimal? value,
        JsonSerializerOptions options)
    {
        if (value is null)
            writer.WriteNullValue();
        else
            writer.WriteNumberValue(value.Value);
    }
}