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

namespace JSMR.Infrastructure.Integrations.DLSite.Serialization;

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

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

            if (string.IsNullOrWhiteSpace(s))
                return null;

            if (DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var dt))
                return dt;
        }

        return null;
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        if (value is DateTime dt)
            writer.WriteStringValue(dt);
        else
            writer.WriteNullValue();
    }
}