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

namespace TrafficLightsSignalR.Schema
{
    public class TimeOnlyConverter : JsonConverter<TimeOnly>
    {
        private const string TimeFormat = "HH:mm"; 

        public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            string timeStr = reader.GetString() ?? throw new JsonException("Invalid time format - null string received.");

            if (TimeOnly.TryParseExact(timeStr, TimeFormat, null, System.Globalization.DateTimeStyles.None, out TimeOnly time))
            {
                return time;
            }

            throw new JsonException("Invalid time format. Expected format: HH:mm");
        }

        public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(TimeFormat));
        }
    }

}
