using System.Text.Json;
using System.Text.Json.Serialization;
namespace Elternbeirat.PocketBase;
///
/// JSON converter that reads and writes a PocketBase date as a calendar date
/// (), ignoring the time-of-day and the time zone.
///
///
/// PocketBase has no date-only field type: it stores every date as a UTC
/// instant with a time-of-day (e.g. an editor's 2 Jan 00:00 Berlin is
/// stored as "2026-01-01 22:00:00.000Z"). The day the editor meant is
/// therefore the day in Berlin, not the day of the raw UTC string. This
/// converter reuses the same UTC->Berlin conversion as
/// and then keeps only the date, so the day
/// shown is the day that was entered -- with no time-of-day and no off-by-one.
///
///
/// Registered on the client's
/// and matched by the field type, so a contract needs no
/// per-field attribute (which would couple the contract to this project).
///
public sealed class DateOnlyConverter : JsonConverter
{
///
///
/// The stored value is not a valid date string.
///
public override DateOnly Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
=> WallClock.Parse(reader.GetString()) is { } berlin
? DateOnly.FromDateTime(berlin)
: default;
///
public override void Write(
Utf8JsonWriter writer,
DateOnly value,
JsonSerializerOptions options)
=> writer.WriteStringValue(WallClock.Format(value.ToDateTime(TimeOnly.MinValue)));
}