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

namespace TakeoutSaaS.Shared.Abstractions.Serialization;

/// <summary>
/// 将 long 类型的雪花 ID 以字符串形式序列化/反序列化，避免前端精度丢失。
/// </summary>
public sealed class SnowflakeIdJsonConverter : JsonConverter<long>
{
    /// <inheritdoc />
    public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return reader.TokenType switch
        {
            JsonTokenType.Number => reader.GetInt64(),
            JsonTokenType.String when long.TryParse(reader.GetString(), out var value) => value,
            JsonTokenType.Null => 0,
            _ => throw new JsonException("无法解析雪花 ID")
        };
    }

    /// <inheritdoc />
    public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value == 0 ? "0" : value.ToString());
    }
}

/// <summary>
/// 可空雪花 ID 转换器。
/// </summary>
public sealed class NullableSnowflakeIdJsonConverter : JsonConverter<long?>
{
    /// <inheritdoc />
    public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return reader.TokenType switch
        {
            JsonTokenType.Number => reader.GetInt64(),
            JsonTokenType.String when long.TryParse(reader.GetString(), out var value) => value,
            JsonTokenType.Null => null,
            _ => throw new JsonException("无法解析雪花 ID")
        };
    }

    /// <inheritdoc />
    public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.HasValue ? value.Value.ToString() : null);
    }
}
