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

namespace MarcusLaw.OutlookAddin.Core.Json
{
    /// <summary>
    /// Reads a JSON value as <see cref="string"/> when the source might be
    /// either a string OR a number (or null). EspoCRM exposes fields such
    /// as Case.number sometimes as JSON numbers (auto-increment) and
    /// sometimes as JSON strings (custom case codes) depending on field
    /// configuration; with a plain <c>string?</c> property the deserializer
    /// would throw on the numeric form.
    /// </summary>
    public sealed class FlexibleStringConverter : JsonConverter<string?>
    {
        public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            switch (reader.TokenType)
            {
                case JsonTokenType.Null:
                    return null;
                case JsonTokenType.String:
                    return reader.GetString();
                case JsonTokenType.Number:
                    if (reader.TryGetInt64(out var l)) return l.ToString(CultureInfo.InvariantCulture);
                    if (reader.TryGetDouble(out var d)) return d.ToString("R", CultureInfo.InvariantCulture);
                    return reader.GetDecimal().ToString(CultureInfo.InvariantCulture);
                case JsonTokenType.True:
                    return "true";
                case JsonTokenType.False:
                    return "false";
                default:
                    reader.Skip();
                    return null;
            }
        }

        public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
        {
            if (value == null) writer.WriteNullValue();
            else writer.WriteStringValue(value);
        }
    }
}
