vld 0.5.0

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! [`ZDate`] / [`ZDateTime`] / [`ZTime`], generic over a [`DateBackend`].
//!
//! A backend only provides the concrete types and parsing of an already
//! shape-checked string (see `primitives::iso`); every rule (accepted formats,
//! bounds, past/future, offsets, messages) lives here, so all backends accept
//! exactly the same inputs:
//!
//! - date: `YYYY-MM-DD` (zero-padded, real calendar day);
//! - datetime: `YYYY-MM-DDTHH:MM:SS[.fraction]` (seconds required, 1-9
//!   fraction digits) followed by `Z` or `±HH:MM`; without the offset the input
//!   is *naive* and is accepted only while [`ZDateTime::naive_allowed`] is on;
//! - time of day: `HH:MM:SS[.fraction]` (seconds required, 1-9 fraction
//!   digits, no offset).
//!
//! Datetimes must land, in UTC, within
//! `0000-01-01T00:00:00Z ..= 9999-12-30T22:00:00.999999999Z` — the range all
//! three libraries can represent (`jiff::Timestamp::MAX` is the upper end) —
//! so e.g. `9999-12-31T00:00:00Z` or `0000-01-01T00:30:00+01:00` is
//! `invalid_date` on every backend.

use serde_json::Value;
use std::fmt::Display;
use std::marker::PhantomData;

use crate::error::{issue_error, DateKind, IssueCode, SizeOrigin, ValidationIssue, VldError};
use crate::primitives::iso::{is_valid_iso_date, is_valid_time_of_day, split_datetime};
use crate::schema::VldSchema;

mod sealed {
    pub trait Sealed {}
}
pub(super) use sealed::Sealed;

/// A date library behind [`ZDate`] / [`ZDateTime`]: `vld::chrono::Chrono`,
/// `vld::jiff::Jiff` or `vld::time::Time`. Sealed.
pub trait DateBackend: Sealed {
    /// Calendar date type.
    type Date: Clone + PartialOrd + Display;
    /// UTC instant type.
    type DateTime: Clone + PartialOrd;
    /// Time-of-day type.
    type Time: Clone + PartialOrd + Display;

    /// Parse a shape-checked `YYYY-MM-DD` string.
    fn parse_date(s: &str) -> Option<Self::Date>;
    /// Parse a shape-checked `HH:MM:SS[.frac]` string.
    fn parse_time(s: &str) -> Option<Self::Time>;
    /// Interpret a shape-checked `YYYY-MM-DDTHH:MM:SS[.frac]` at `offset_seconds`, as UTC.
    fn naive_to_utc(naive: &str, offset_seconds: i32) -> Option<Self::DateTime>;
    /// Current UTC date.
    fn today() -> Self::Date;
    /// Current instant.
    fn now() -> Self::DateTime;
    /// RFC 3339 form (messages, JSON Schema).
    fn format_datetime(dt: &Self::DateTime) -> String;
    /// `HH:MM:SS[.frac]` form (messages, JSON Schema).
    fn format_time(t: &Self::Time) -> String {
        t.to_string()
    }
}

fn parse_date<B: DateBackend>(s: &str) -> Option<B::Date> {
    is_valid_iso_date(s).then(|| B::parse_date(s)).flatten()
}

fn parse_time<B: DateBackend>(s: &str) -> Option<B::Time> {
    is_valid_time_of_day(s).then(|| B::parse_time(s)).flatten()
}

/// Strict datetime parse; `naive_offset` is applied when the input has no offset
/// (`None` = naive input rejected). Returns the UTC instant and the input offset.
fn parse_datetime<B: DateBackend>(
    s: &str,
    naive_offset: Option<i32>,
) -> Option<(B::DateTime, Option<i32>)> {
    let (naive, offset) = split_datetime(s)?;
    let at = offset.or(naive_offset)?;
    if !in_common_range(&naive, at) {
        return None;
    }
    let dt = B::naive_to_utc(&naive, at)?;
    Some((dt, offset))
}

/// Whether `naive` at `offset_seconds` is a UTC instant every backend can
/// represent: `0000-01-01T00:00:00Z ..= 9999-12-30T22:00:00.999999999Z`
/// (the upper end is `jiff::Timestamp::MAX`). Only the first and the last two
/// days of that range need a look, as `|offset| < 24h`.
fn in_common_range(naive: &str, offset_seconds: i32) -> bool {
    // Shape-checked by `split_datetime`: `YYYY-MM-DDTHH:MM:SS...`, all ASCII.
    let num = |r: std::ops::Range<usize>| naive[r].parse::<i32>().unwrap_or(0);
    let secs = num(11..13) * 3600 + num(14..16) * 60 + num(17..19) - offset_seconds;
    match &naive[..10] {
        "0000-01-01" => secs >= 0,
        "9999-12-30" => secs <= 22 * 3600,
        "9999-12-31" => secs <= 22 * 3600 - 86_400,
        _ => true,
    }
}

fn check_offset(offset_seconds: i32) -> i32 {
    if offset_seconds.unsigned_abs() >= 86_400 {
        panic!(
            "Invalid timezone offset seconds: {} (expected range -86399..=86399)",
            offset_seconds
        );
    }
    offset_seconds
}

fn format_offset(offset_seconds: i32) -> String {
    let sign = if offset_seconds >= 0 { '+' } else { '-' };
    let abs = offset_seconds.unsigned_abs();
    format!("{}{:02}:{:02}", sign, abs / 3600, (abs % 3600) / 60)
}

/// A bound: the value, its display form (for messages / JSON Schema) and an
/// optional custom message.
#[derive(Clone)]
struct Bound<T> {
    value: T,
    display: String,
    msg: Option<String>,
}

/// Bounds shared by `ZDate` and `ZDateTime`. Out-of-range values report
/// `TooSmall` / `TooBig` (origin `Date` / `DateTime`, bound as a string);
/// past/future checks report `NotInPast` / `NotInFuture`.
#[derive(Clone)]
struct Bounds<T> {
    min: Option<Bound<T>>,
    max: Option<Bound<T>>,
    /// `Some(custom message)` when the check is on.
    past: Option<Option<String>>,
    future: Option<Option<String>>,
}

impl<T: PartialOrd> Bounds<T> {
    fn new() -> Self {
        Self {
            min: None,
            max: None,
            past: None,
            future: None,
        }
    }

    fn set_min(&mut self, value: T, display: String) {
        self.min = Some(Bound {
            value,
            display,
            msg: None,
        });
    }

    fn set_max(&mut self, value: T, display: String) {
        self.max = Some(Bound {
            value,
            display,
            msg: None,
        });
    }

    fn check(&self, v: &T, now: impl FnOnce() -> T, kind: DateKind, value: &Value) -> VldError {
        let origin = match kind {
            DateKind::Date => SizeOrigin::Date,
            DateKind::DateTime => SizeOrigin::DateTime,
            DateKind::Time => SizeOrigin::Time,
        };
        let mut errors = VldError::new();
        let mut push = |code, msg: Option<&String>| {
            errors
                .issues
                .push(ValidationIssue::with_override(code, msg).with_received(value))
        };
        if let Some(min) = self.min.as_ref().filter(|b| *v < b.value) {
            push(
                IssueCode::TooSmall {
                    origin,
                    minimum: Value::String(min.display.clone()),
                    inclusive: true,
                },
                min.msg.as_ref(),
            );
        }
        if let Some(max) = self.max.as_ref().filter(|b| *v > b.value) {
            push(
                IssueCode::TooBig {
                    origin,
                    maximum: Value::String(max.display.clone()),
                    inclusive: true,
                },
                max.msg.as_ref(),
            );
        }
        if self.past.is_some() || self.future.is_some() {
            let now = now();
            if let Some(msg) = self.past.as_ref().filter(|_| *v >= now) {
                push(IssueCode::NotInPast { kind }, msg.as_ref());
            }
            if let Some(msg) = self.future.as_ref().filter(|_| *v <= now) {
                push(IssueCode::NotInFuture { kind }, msg.as_ref());
            }
        }
        errors
    }

    /// `base` plus `formatMinimum` / `formatMaximum` and `x-past` / `x-future`.
    #[cfg(feature = "openapi")]
    fn json_schema(&self, mut schema: Value) -> Value {
        if let Some(b) = &self.min {
            schema["formatMinimum"] = serde_json::json!(b.display);
        }
        if let Some(b) = &self.max {
            schema["formatMaximum"] = serde_json::json!(b.display);
        }
        if self.past.is_some() {
            schema["x-past"] = Value::Bool(true);
        }
        if self.future.is_some() {
            schema["x-future"] = Value::Bool(true);
        }
        schema
    }
}

/// Schema for date validation. Parses strict ISO 8601 dates (`YYYY-MM-DD`)
/// into the backend's date type (`chrono::NaiveDate`, `jiff::civil::Date` or
/// `time::Date`).
///
/// Created via `vld::chrono::date()`, `vld::jiff::date()` or `vld::time::date()`
/// (or `vld::date()` when exactly one backend is enabled).
#[derive(Clone)]
pub struct ZDate<B: DateBackend> {
    bounds: Bounds<B::Date>,
    custom_type_error: Option<String>,
    _backend: PhantomData<fn() -> B>,
}

impl<B: DateBackend> ZDate<B> {
    pub fn new() -> Self {
        Self {
            bounds: Bounds::new(),
            custom_type_error: None,
            _backend: PhantomData,
        }
    }

    /// Set a custom error message for type mismatch (non-string input).
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    fn literal(date: &str) -> B::Date {
        parse_date::<B>(date).unwrap_or_else(|| panic!("Invalid date literal: {}", date))
    }

    /// Minimum date (inclusive). Accepts `"YYYY-MM-DD"`; panics on an invalid literal.
    pub fn min(self, date: &str) -> Self {
        self.min_date(Self::literal(date))
    }

    /// Minimum date (inclusive) from a backend date value.
    pub fn min_date(mut self, date: B::Date) -> Self {
        let display = date.to_string();
        self.bounds.set_min(date, display);
        self
    }

    /// Maximum date (inclusive). Accepts `"YYYY-MM-DD"`; panics on an invalid literal.
    pub fn max(self, date: &str) -> Self {
        self.max_date(Self::literal(date))
    }

    /// Maximum date (inclusive) from a backend date value.
    pub fn max_date(mut self, date: B::Date) -> Self {
        let display = date.to_string();
        self.bounds.set_max(date, display);
        self
    }

    /// Date must be in the past (before today, UTC).
    pub fn past(mut self) -> Self {
        self.bounds.past = Some(None);
        self
    }

    /// Date must be in the past (before today), with custom message.
    pub fn past_msg(mut self, msg: impl Into<String>) -> Self {
        self.bounds.past = Some(Some(msg.into()));
        self
    }

    /// Date must be in the future (after today, UTC).
    pub fn future(mut self) -> Self {
        self.bounds.future = Some(None);
        self
    }

    /// Date must be in the future (after today), with custom message.
    pub fn future_msg(mut self, msg: impl Into<String>) -> Self {
        self.bounds.future = Some(Some(msg.into()));
        self
    }
}

impl<B: DateBackend> Default for ZDate<B> {
    fn default() -> Self {
        Self::new()
    }
}

impl<B: DateBackend> VldSchema for ZDate<B> {
    type Output = B::Date;

    fn output_json(&self, o: &B::Date) -> Option<Value> {
        Some(Value::String(o.to_string()))
    }

    fn parse_value(&self, value: &Value) -> Result<B::Date, VldError> {
        let s = value
            .as_str()
            .ok_or_else(|| crate::primitives::type_error(&self.custom_type_error, "date", value))?;
        let date = parse_date::<B>(s).ok_or_else(|| {
            VldError::from_code_with_value(
                IssueCode::InvalidDate {
                    kind: DateKind::Date,
                },
                value,
            )
        })?;
        let errors = self.bounds.check(&date, B::today, DateKind::Date, value);
        if errors.is_empty() {
            Ok(date)
        } else {
            Err(errors)
        }
    }
}

/// `{"type": "string", "format": "date"}`; `min`/`max` become
/// `formatMinimum`/`formatMaximum`, `past()`/`future()` `x-past`/`x-future`.
#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::JsonSchema for ZDate<B> {
    fn json_schema(&self) -> Value {
        self.bounds
            .json_schema(serde_json::json!({"type": "string", "format": "date"}))
    }
}

#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::CollectNestedSchemas for ZDate<B> {}

/// Offset required by [`ZDateTime::timezone_offset_only`].
#[derive(Clone)]
struct RequiredOffset {
    seconds: i32,
    msg: Option<String>,
}

impl RequiredOffset {
    fn error(&self, value: &Value) -> VldError {
        issue_error(
            IssueCode::InvalidTimezoneOffset {
                expected: format_offset(self.seconds),
            },
            self.msg.as_ref(),
            value,
        )
    }
}

/// Schema for datetime validation. Parses strict RFC 3339 datetimes into the
/// backend's UTC instant (`chrono::DateTime<Utc>`, `jiff::Timestamp` or
/// `time::OffsetDateTime` at UTC).
///
/// Created via `vld::chrono::datetime()`, `vld::jiff::datetime()` or
/// `vld::time::datetime()` (or `vld::datetime()` when exactly one backend is
/// enabled).
///
/// Accepts `YYYY-MM-DDTHH:MM:SS[.fraction]` plus `Z` or `±HH:MM`, e.g.
/// `2024-01-15T10:30:00Z`, `2024-01-15T10:30:00+03:00`,
/// `2024-01-15T10:30:00.123Z`. Naive input (no offset) is accepted by default
/// and interpreted in [`naive_timezone_offset`](Self::naive_timezone_offset)
/// (UTC unless set); see [`naive_allowed`](Self::naive_allowed).
#[derive(Clone)]
pub struct ZDateTime<B: DateBackend> {
    bounds: Bounds<B::DateTime>,
    allow_naive: bool,
    naive_offset: i32,
    required_timezone_offset: Option<RequiredOffset>,
    custom_type_error: Option<String>,
    _backend: PhantomData<fn() -> B>,
}

impl<B: DateBackend> ZDateTime<B> {
    pub fn new() -> Self {
        Self {
            bounds: Bounds::new(),
            allow_naive: true,
            naive_offset: 0,
            required_timezone_offset: None,
            custom_type_error: None,
            _backend: PhantomData,
        }
    }

    /// Set a custom error message for type mismatch (non-string input).
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    fn literal(dt: &str) -> B::DateTime {
        parse_datetime::<B>(dt, None)
            .map(|(dt, _)| dt)
            .unwrap_or_else(|| panic!("Invalid datetime literal: {}", dt))
    }

    /// Minimum datetime (inclusive). Accepts RFC 3339 with offset; panics on an invalid literal.
    pub fn min(self, dt: &str) -> Self {
        self.min_datetime(Self::literal(dt))
    }

    /// Minimum datetime (inclusive) from a backend UTC datetime.
    pub fn min_datetime(mut self, dt: B::DateTime) -> Self {
        let display = B::format_datetime(&dt);
        self.bounds.set_min(dt, display);
        self
    }

    /// Maximum datetime (inclusive). Accepts RFC 3339 with offset; panics on an invalid literal.
    pub fn max(self, dt: &str) -> Self {
        self.max_datetime(Self::literal(dt))
    }

    /// Maximum datetime (inclusive) from a backend UTC datetime.
    pub fn max_datetime(mut self, dt: B::DateTime) -> Self {
        let display = B::format_datetime(&dt);
        self.bounds.set_max(dt, display);
        self
    }

    /// Datetime must be in the past.
    pub fn past(mut self) -> Self {
        self.bounds.past = Some(None);
        self
    }

    /// Datetime must be in the past, with custom message.
    pub fn past_msg(mut self, msg: impl Into<String>) -> Self {
        self.bounds.past = Some(Some(msg.into()));
        self
    }

    /// Datetime must be in the future.
    pub fn future(mut self) -> Self {
        self.bounds.future = Some(None);
        self
    }

    /// Datetime must be in the future, with custom message.
    pub fn future_msg(mut self, msg: impl Into<String>) -> Self {
        self.bounds.future = Some(Some(msg.into()));
        self
    }

    /// Allow or disallow naive datetime input without timezone.
    ///
    /// Default is `true` for backward compatibility. Ignored (naive input is
    /// always rejected) once [`timezone_offset_only`](Self::timezone_offset_only) is set.
    pub fn naive_allowed(mut self, allowed: bool) -> Self {
        self.allow_naive = allowed;
        self
    }

    /// Strict mode: require timezone in datetime input (RFC 3339).
    pub fn with_timezone_only(self) -> Self {
        self.naive_allowed(false)
    }

    /// Interpret naive datetimes (`YYYY-MM-DDTHH:MM:SS`) in the provided timezone offset.
    ///
    /// The parsed output is still normalized to UTC.
    ///
    /// # Panics
    /// If `|offset_seconds| >= 86400`.
    pub fn naive_timezone_offset(mut self, offset_seconds: i32) -> Self {
        self.naive_offset = check_offset(offset_seconds);
        self
    }

    /// Require the input to carry an explicit offset equal to `offset_seconds`.
    ///
    /// Naive input (no offset) is rejected as well — the offset cannot be
    /// verified — regardless of [`naive_allowed`](Self::naive_allowed).
    ///
    /// # Panics
    /// If `|offset_seconds| >= 86400`.
    pub fn timezone_offset_only(mut self, offset_seconds: i32) -> Self {
        self.required_timezone_offset = Some(RequiredOffset {
            seconds: check_offset(offset_seconds),
            msg: None,
        });
        self
    }

    /// Same as [`timezone_offset_only`](Self::timezone_offset_only), with custom message.
    pub fn timezone_offset_only_msg(mut self, offset_seconds: i32, msg: impl Into<String>) -> Self {
        self.required_timezone_offset = Some(RequiredOffset {
            seconds: check_offset(offset_seconds),
            msg: Some(msg.into()),
        });
        self
    }
}

impl<B: DateBackend> Default for ZDateTime<B> {
    fn default() -> Self {
        Self::new()
    }
}

impl<B: DateBackend> VldSchema for ZDateTime<B> {
    type Output = B::DateTime;

    fn output_json(&self, o: &B::DateTime) -> Option<Value> {
        Some(Value::String(B::format_datetime(o)))
    }

    fn parse_value(&self, value: &Value) -> Result<B::DateTime, VldError> {
        let s = value.as_str().ok_or_else(|| {
            crate::primitives::type_error(&self.custom_type_error, "datetime", value)
        })?;

        let naive_offset = (self.allow_naive && self.required_timezone_offset.is_none())
            .then_some(self.naive_offset);
        let (dt, offset) = parse_datetime::<B>(s, naive_offset).ok_or_else(|| {
            // A well-formed naive input rejected only because of the offset rule.
            if let (Some(required), Some((_, None))) =
                (&self.required_timezone_offset, split_datetime(s))
            {
                return required.error(value);
            }
            VldError::from_code_with_value(
                IssueCode::InvalidDate {
                    kind: DateKind::DateTime,
                },
                value,
            )
        })?;

        if let Some(required) = &self.required_timezone_offset {
            if offset != Some(required.seconds) {
                return Err(required.error(value));
            }
        }

        let errors = self.bounds.check(&dt, B::now, DateKind::DateTime, value);
        if errors.is_empty() {
            Ok(dt)
        } else {
            Err(errors)
        }
    }
}

/// `{"type": "string", "format": "date-time"}` when an offset is required
/// ([`with_timezone_only`](ZDateTime::with_timezone_only),
/// [`timezone_offset_only`](ZDateTime::timezone_offset_only)). By default naive
/// input is accepted too, which `date-time` forbids, so the schema is
/// `{"type": "string", "anyOf": [{"format": "date-time"}, {"pattern": <naive>}]}`.
/// `min`/`max` become `formatMinimum`/`formatMaximum`, `past()`/`future()`
/// `x-past`/`x-future`.
#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::JsonSchema for ZDateTime<B> {
    fn json_schema(&self) -> Value {
        let base = if self.allow_naive && self.required_timezone_offset.is_none() {
            serde_json::json!({
                "type": "string",
                "anyOf": [
                    {"format": "date-time"},
                    {"format": "naive-date-time", "pattern": NAIVE_DATETIME_PATTERN},
                ],
            })
        } else {
            serde_json::json!({"type": "string", "format": "date-time"})
        };
        self.bounds.json_schema(base)
    }
}

/// Naive `YYYY-MM-DDTHH:MM:SS[.frac]` (the calendar is checked by the parser).
#[cfg(feature = "openapi")]
const NAIVE_DATETIME_PATTERN: &str =
    r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])[Tt]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,9})?$";

/// `HH:MM:SS[.frac]` with field ranges checked.
#[cfg(feature = "openapi")]
const TIME_OF_DAY_PATTERN: &str = r"^([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,9})?$";

#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::CollectNestedSchemas for ZDateTime<B> {}

/// Schema for a time of day: `HH:MM:SS[.fraction]` (no offset) into the
/// backend's time type (`chrono::NaiveTime`, `jiff::civil::Time` or
/// `time::Time`).
///
/// Created via `vld::chrono::time()`, `vld::jiff::time()` or `vld::time::time()`
/// (or `vld::time_of_day()` when exactly one backend is enabled). Malformed
/// input fails with `invalid_date` (kind `time`); bounds with `too_small` /
/// `too_big` (origin `time`). JSON Schema: a `pattern` for `HH:MM:SS[.frac]`
/// (`format: time` would require an offset).
#[derive(Clone)]
pub struct ZTime<B: DateBackend> {
    bounds: Bounds<B::Time>,
    custom_type_error: Option<String>,
    _backend: PhantomData<fn() -> B>,
}

impl<B: DateBackend> ZTime<B> {
    pub fn new() -> Self {
        Self {
            bounds: Bounds::new(),
            custom_type_error: None,
            _backend: PhantomData,
        }
    }

    /// Set a custom error message for type mismatch (non-string input).
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    fn literal(time: &str) -> B::Time {
        parse_time::<B>(time).unwrap_or_else(|| panic!("Invalid time literal: {}", time))
    }

    /// Earliest time (inclusive). Accepts `"HH:MM:SS[.frac]"`; panics on an invalid literal.
    pub fn min(mut self, time: &str) -> Self {
        self.bounds.set_min(Self::literal(time), time.to_string());
        self
    }

    /// Earliest time (inclusive) from a backend time value.
    pub fn min_time(mut self, time: B::Time) -> Self {
        let display = B::format_time(&time);
        self.bounds.set_min(time, display);
        self
    }

    /// Latest time (inclusive). Accepts `"HH:MM:SS[.frac]"`; panics on an invalid literal.
    pub fn max(mut self, time: &str) -> Self {
        self.bounds.set_max(Self::literal(time), time.to_string());
        self
    }

    /// Latest time (inclusive) from a backend time value.
    pub fn max_time(mut self, time: B::Time) -> Self {
        let display = B::format_time(&time);
        self.bounds.set_max(time, display);
        self
    }
}

impl<B: DateBackend> Default for ZTime<B> {
    fn default() -> Self {
        Self::new()
    }
}

impl<B: DateBackend> VldSchema for ZTime<B> {
    type Output = B::Time;

    fn output_json(&self, o: &B::Time) -> Option<Value> {
        Some(Value::String(B::format_time(o)))
    }

    fn parse_value(&self, value: &Value) -> Result<B::Time, VldError> {
        let s = value
            .as_str()
            .ok_or_else(|| crate::primitives::type_error(&self.custom_type_error, "time", value))?;
        let time = parse_time::<B>(s).ok_or_else(|| {
            VldError::from_code_with_value(
                IssueCode::InvalidDate {
                    kind: DateKind::Time,
                },
                value,
            )
        })?;
        // No past/future checks for a time of day, so `now` is never called.
        let errors = self
            .bounds
            .check(&time, || time.clone(), DateKind::Time, value);
        if errors.is_empty() {
            Ok(time)
        } else {
            Err(errors)
        }
    }
}

/// `{"type": "string", "format": "partial-time", "pattern": ...}` — RFC 3339
/// `partial-time` (not `format: time`, which requires an offset; validators
/// ignore the unknown format and use the pattern); `min`/`max` become
/// `formatMinimum`/`formatMaximum`.
#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::JsonSchema for ZTime<B> {
    fn json_schema(&self) -> Value {
        self.bounds.json_schema(serde_json::json!({
            "type": "string",
            "format": "partial-time",
            "pattern": TIME_OF_DAY_PATTERN,
        }))
    }
}

#[cfg(feature = "openapi")]
impl<B: DateBackend> crate::openapi::CollectNestedSchemas for ZTime<B> {}