genai-rs 0.8.0

A Rust client library for Google's Generative AI (Gemini) API with streaming, function calling, and multi-turn conversations
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Webhook types for the `/v1beta/webhooks` resource and the per-request
//! `webhook_config` field.
//!
//! Webhooks let the API push events (batch completion, interaction lifecycle,
//! video generation) to your HTTPS endpoint instead of requiring polling.
//!
//! - Manage registered webhooks with the [`Client`](crate::Client) methods
//!   `create_webhook`, `get_webhook`, `list_webhooks`, `update_webhook`,
//!   `delete_webhook`, `ping_webhook`, and `rotate_webhook_signing_secret`.
//! - Route a single request's events to ad-hoc URIs with
//!   [`WebhookConfig`] via
//!   [`InteractionBuilder::with_webhook_config()`](crate::InteractionBuilder::with_webhook_config).
//!
//! See `docs/AGENTS_AND_BACKGROUND.md` for the full background-execution +
//! webhook flow.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

/// An event type a webhook can subscribe to.
///
/// This enum is marked `#[non_exhaustive]` for forward compatibility.
/// New event types may be added in future API versions.
///
/// # Wire Format
///
/// Serializes as dotted lowercase strings: `"batch.succeeded"`,
/// `"interaction.completed"`, `"video.generated"`, etc.
///
/// # Evergreen Pattern
///
/// Unknown values from the API deserialize into the `Unknown` variant,
/// preserving the original data for debugging and roundtrip serialization.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum WebhookEvent {
    /// Batch processing finished successfully.
    BatchSucceeded,
    /// Batch was not processed within the 48h timeframe.
    BatchExpired,
    /// Batch job failed.
    BatchFailed,
    /// Interaction requires action (e.g., function calling).
    InteractionRequiresAction,
    /// Interaction completed successfully.
    InteractionCompleted,
    /// Interaction failed.
    InteractionFailed,
    /// Video generation completed.
    VideoGenerated,
    /// Unknown variant for forward compatibility (Evergreen pattern)
    Unknown {
        /// The unrecognized event type from the API
        event_type: String,
        /// The raw JSON value, preserved for debugging and roundtrip
        data: serde_json::Value,
    },
}

impl WebhookEvent {
    /// Returns true if this is an unknown webhook event.
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown { .. })
    }

    /// Returns the event type name if this is an unknown webhook event.
    #[must_use]
    pub fn unknown_event_type(&self) -> Option<&str> {
        match self {
            Self::Unknown { event_type, .. } => Some(event_type),
            _ => None,
        }
    }

    /// Returns the preserved data if this is an unknown webhook event.
    #[must_use]
    pub fn unknown_data(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Unknown { data, .. } => Some(data),
            _ => None,
        }
    }

    const fn as_wire(&self) -> Option<&'static str> {
        match self {
            Self::BatchSucceeded => Some("batch.succeeded"),
            Self::BatchExpired => Some("batch.expired"),
            Self::BatchFailed => Some("batch.failed"),
            Self::InteractionRequiresAction => Some("interaction.requires_action"),
            Self::InteractionCompleted => Some("interaction.completed"),
            Self::InteractionFailed => Some("interaction.failed"),
            Self::VideoGenerated => Some("video.generated"),
            Self::Unknown { .. } => None,
        }
    }
}

impl fmt::Display for WebhookEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_wire() {
            Some(wire) => write!(f, "{}", wire),
            None => match self {
                Self::Unknown { event_type, .. } => write!(f, "{}", event_type),
                _ => unreachable!("known events always have a wire form"),
            },
        }
    }
}

impl Serialize for WebhookEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self.as_wire() {
            Some(wire) => serializer.serialize_str(wire),
            None => match self {
                Self::Unknown { event_type, .. } => serializer.serialize_str(event_type),
                _ => unreachable!("known events always have a wire form"),
            },
        }
    }
}

impl<'de> Deserialize<'de> for WebhookEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value.as_str() {
            Some("batch.succeeded") => Ok(Self::BatchSucceeded),
            Some("batch.expired") => Ok(Self::BatchExpired),
            Some("batch.failed") => Ok(Self::BatchFailed),
            Some("interaction.requires_action") => Ok(Self::InteractionRequiresAction),
            Some("interaction.completed") => Ok(Self::InteractionCompleted),
            Some("interaction.failed") => Ok(Self::InteractionFailed),
            Some("video.generated") => Ok(Self::VideoGenerated),
            Some(other) => {
                tracing::warn!(
                    "Encountered unknown WebhookEvent '{}' - using Unknown variant (Evergreen)",
                    other
                );
                Ok(Self::Unknown {
                    event_type: other.to_string(),
                    data: value,
                })
            }
            None => {
                let event_type = format!("<non-string: {}>", value);
                tracing::warn!(
                    "WebhookEvent received non-string value: {}. \
                     Preserving in Unknown variant.",
                    value
                );
                Ok(Self::Unknown {
                    event_type,
                    data: value,
                })
            }
        }
    }
}

/// The state of a registered webhook (output only).
///
/// This enum is marked `#[non_exhaustive]` for forward compatibility.
///
/// # Wire Format
///
/// Serializes as lowercase snake_case strings: `"enabled"`, `"disabled"`,
/// `"disabled_due_to_failed_deliveries"`.
///
/// # Evergreen Pattern
///
/// Unknown values from the API deserialize into the `Unknown` variant,
/// preserving the original data for debugging and roundtrip serialization.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum WebhookState {
    /// Webhook is active and receiving events.
    Enabled,
    /// Webhook is disabled and receives no events.
    Disabled,
    /// The API disabled the webhook after repeated delivery failures.
    DisabledDueToFailedDeliveries,
    /// Unknown variant for forward compatibility (Evergreen pattern)
    Unknown {
        /// The unrecognized state type from the API
        state_type: String,
        /// The raw JSON value, preserved for debugging and roundtrip
        data: serde_json::Value,
    },
}

impl WebhookState {
    /// Returns true if this is an unknown webhook state.
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown { .. })
    }

    /// Returns the state type name if this is an unknown webhook state.
    #[must_use]
    pub fn unknown_state_type(&self) -> Option<&str> {
        match self {
            Self::Unknown { state_type, .. } => Some(state_type),
            _ => None,
        }
    }

    /// Returns the preserved data if this is an unknown webhook state.
    #[must_use]
    pub fn unknown_data(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Unknown { data, .. } => Some(data),
            _ => None,
        }
    }
}

impl Serialize for WebhookState {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Enabled => serializer.serialize_str("enabled"),
            Self::Disabled => serializer.serialize_str("disabled"),
            Self::DisabledDueToFailedDeliveries => {
                serializer.serialize_str("disabled_due_to_failed_deliveries")
            }
            Self::Unknown { state_type, .. } => serializer.serialize_str(state_type),
        }
    }
}

impl<'de> Deserialize<'de> for WebhookState {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value.as_str() {
            Some("enabled") => Ok(Self::Enabled),
            Some("disabled") => Ok(Self::Disabled),
            Some("disabled_due_to_failed_deliveries") => Ok(Self::DisabledDueToFailedDeliveries),
            Some(other) => {
                tracing::warn!(
                    "Encountered unknown WebhookState '{}' - using Unknown variant (Evergreen)",
                    other
                );
                Ok(Self::Unknown {
                    state_type: other.to_string(),
                    data: value,
                })
            }
            None => {
                let state_type = format!("<non-string: {}>", value);
                tracing::warn!(
                    "WebhookState received non-string value: {}. \
                     Preserving in Unknown variant.",
                    value
                );
                Ok(Self::Unknown {
                    state_type,
                    data: value,
                })
            }
        }
    }
}

/// A signing secret used to verify webhook payloads (output only).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct SigningSecret {
    /// Truncated version of the signing secret (for identification).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub truncated_secret: Option<String>,
    /// Expiration timestamp of the signing secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_time: Option<DateTime<Utc>>,
}

/// A Webhook resource.
///
/// Create with [`Webhook::new()`] and register it via
/// [`Client::create_webhook()`](crate::Client::create_webhook). Fields marked
/// "output only" are populated by the API and ignored on create.
///
/// # Example
///
/// ```
/// use genai_rs::{Webhook, WebhookEvent};
///
/// let webhook = Webhook::new(
///     "https://example.com/hooks/genai",
///     vec![WebhookEvent::InteractionCompleted, WebhookEvent::InteractionFailed],
/// )
/// .with_name("my-hook");
/// ```
#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Webhook {
    /// The URI to which webhook events will be sent (required).
    pub uri: String,
    /// The events that the webhook is subscribed to (required).
    pub subscribed_events: Vec<WebhookEvent>,
    /// Optional user-provided name of the webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Output only. The ID of the webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Output only. The state of the webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<WebhookState>,
    /// Output only. The signing secrets associated with this webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signing_secrets: Option<Vec<SigningSecret>>,
    /// Output only. The new signing secret. Only populated on create —
    /// store it securely, it is not returned again.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_signing_secret: Option<String>,
    /// Output only. When the webhook was created.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_time: Option<DateTime<Utc>>,
    /// Output only. When the webhook was last updated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_time: Option<DateTime<Utc>>,
}

// Custom Debug that redacts the one-time signing secret (mirrors the
// api_key redaction on `Client` / `HttpContext`).
impl std::fmt::Debug for Webhook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Webhook")
            .field("uri", &self.uri)
            .field("subscribed_events", &self.subscribed_events)
            .field("name", &self.name)
            .field("id", &self.id)
            .field("state", &self.state)
            .field("signing_secrets", &self.signing_secrets)
            .field(
                "new_signing_secret",
                &self.new_signing_secret.as_ref().map(|_| "[REDACTED]"),
            )
            .field("create_time", &self.create_time)
            .field("update_time", &self.update_time)
            .finish()
    }
}

impl Webhook {
    /// Creates a new webhook definition for registration.
    #[must_use]
    pub fn new(uri: impl Into<String>, subscribed_events: Vec<WebhookEvent>) -> Self {
        Self {
            uri: uri.into(),
            subscribed_events,
            ..Default::default()
        }
    }

    /// Sets the user-provided name of the webhook.
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

/// A partial update for a webhook (`PATCH /v1beta/webhooks/{id}`).
///
/// Only the set fields are updated. Pair with an `update_mask` in
/// [`Client::update_webhook()`](crate::Client::update_webhook) to control
/// which fields the server applies.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct WebhookUpdate {
    /// New user-provided name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New destination URI.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<String>,
    /// New event subscription list.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscribed_events: Option<Vec<WebhookEvent>>,
    /// New state (`enabled` / `disabled`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<WebhookState>,
}

impl WebhookUpdate {
    /// Creates an empty update.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a new name.
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets a new destination URI.
    #[must_use]
    pub fn with_uri(mut self, uri: impl Into<String>) -> Self {
        self.uri = Some(uri.into());
        self
    }

    /// Sets a new event subscription list.
    #[must_use]
    pub fn with_subscribed_events(mut self, events: Vec<WebhookEvent>) -> Self {
        self.subscribed_events = Some(events);
        self
    }

    /// Sets a new state.
    #[must_use]
    pub fn with_state(mut self, state: WebhookState) -> Self {
        self.state = Some(state);
        self
    }
}

/// Revocation behavior for previous signing secrets when rotating.
///
/// This enum is marked `#[non_exhaustive]` for forward compatibility.
///
/// # Wire Format
///
/// Serializes as `"revoke_previous_secrets_after_h24"` or
/// `"revoke_previous_secrets_immediately"`.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RevocationBehavior {
    /// Previous secrets stay valid for 24 hours (safe rollover).
    RevokePreviousSecretsAfterH24,
    /// Previous secrets are revoked immediately.
    RevokePreviousSecretsImmediately,
    /// Unknown variant for forward compatibility (Evergreen pattern)
    Unknown {
        /// The unrecognized behavior type from the API
        behavior_type: String,
        /// The raw JSON value, preserved for debugging and roundtrip
        data: serde_json::Value,
    },
}

impl RevocationBehavior {
    /// Returns true if this is an unknown revocation behavior.
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown { .. })
    }

    /// Returns the behavior type name if this is an unknown revocation behavior.
    #[must_use]
    pub fn unknown_behavior_type(&self) -> Option<&str> {
        match self {
            Self::Unknown { behavior_type, .. } => Some(behavior_type),
            _ => None,
        }
    }

    /// Returns the preserved data if this is an unknown revocation behavior.
    #[must_use]
    pub fn unknown_data(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Unknown { data, .. } => Some(data),
            _ => None,
        }
    }
}

impl Serialize for RevocationBehavior {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::RevokePreviousSecretsAfterH24 => {
                serializer.serialize_str("revoke_previous_secrets_after_h24")
            }
            Self::RevokePreviousSecretsImmediately => {
                serializer.serialize_str("revoke_previous_secrets_immediately")
            }
            Self::Unknown { behavior_type, .. } => serializer.serialize_str(behavior_type),
        }
    }
}

impl<'de> Deserialize<'de> for RevocationBehavior {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value.as_str() {
            Some("revoke_previous_secrets_after_h24") => Ok(Self::RevokePreviousSecretsAfterH24),
            Some("revoke_previous_secrets_immediately") => {
                Ok(Self::RevokePreviousSecretsImmediately)
            }
            Some(other) => {
                tracing::warn!(
                    "Encountered unknown RevocationBehavior '{}' - using Unknown variant (Evergreen)",
                    other
                );
                Ok(Self::Unknown {
                    behavior_type: other.to_string(),
                    data: value,
                })
            }
            None => {
                let behavior_type = format!("<non-string: {}>", value);
                tracing::warn!(
                    "RevocationBehavior received non-string value: {}. \
                     Preserving in Unknown variant.",
                    value
                );
                Ok(Self::Unknown {
                    behavior_type,
                    data: value,
                })
            }
        }
    }
}

/// Response for `GET /v1beta/webhooks` (list).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct WebhookListResponse {
    /// The webhooks on this page.
    pub webhooks: Vec<Webhook>,
    /// Token for the next page. Absent when there are no more pages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_page_token: Option<String>,
}

/// Response for `POST /v1beta/webhooks/{id}:rotateSigningSecret`.
#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RotateSigningSecretResponse {
    /// The newly generated signing secret. Store it securely — it is not
    /// returned again.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secret: Option<String>,
}

// Custom Debug that redacts the rotated signing secret (mirrors the
// api_key redaction on `Client` / `HttpContext`).
impl std::fmt::Debug for RotateSigningSecretResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RotateSigningSecretResponse")
            .field("secret", &self.secret.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

/// Per-request webhook configuration (`webhook_config` on an interaction
/// request).
///
/// When set, events for this request are delivered to `uris` instead of the
/// registered webhooks, and `user_metadata` is echoed back on each event.
///
/// # Example
///
/// ```
/// use genai_rs::WebhookConfig;
///
/// let config = WebhookConfig::new()
///     .with_uris(vec!["https://example.com/hooks/genai".to_string()])
///     .with_user_metadata(serde_json::json!({"job": "nightly-report"}));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct WebhookConfig {
    /// If set, these webhook URIs are used for events from this request
    /// instead of the registered webhooks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uris: Option<Vec<String>>,
    /// User metadata returned on each event emission to the webhooks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_metadata: Option<serde_json::Value>,
}

impl WebhookConfig {
    /// Creates an empty webhook config.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the override webhook URIs for this request.
    #[must_use]
    pub fn with_uris(mut self, uris: Vec<String>) -> Self {
        self.uris = Some(uris);
        self
    }

    /// Sets the user metadata echoed back on each event emission.
    #[must_use]
    pub fn with_user_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.user_metadata = Some(metadata);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_webhook_event_wire_roundtrip() {
        for (event, wire) in [
            (WebhookEvent::BatchSucceeded, "\"batch.succeeded\""),
            (WebhookEvent::BatchExpired, "\"batch.expired\""),
            (WebhookEvent::BatchFailed, "\"batch.failed\""),
            (
                WebhookEvent::InteractionRequiresAction,
                "\"interaction.requires_action\"",
            ),
            (
                WebhookEvent::InteractionCompleted,
                "\"interaction.completed\"",
            ),
            (WebhookEvent::InteractionFailed, "\"interaction.failed\""),
            (WebhookEvent::VideoGenerated, "\"video.generated\""),
        ] {
            assert_eq!(serde_json::to_string(&event).unwrap(), wire);
            let parsed: WebhookEvent = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, event);
        }
    }

    #[test]
    fn test_webhook_event_unknown_roundtrip() {
        let unknown: WebhookEvent = serde_json::from_str("\"file.generated\"").unwrap();
        assert!(unknown.is_unknown());
        assert_eq!(unknown.unknown_event_type(), Some("file.generated"));
        assert!(unknown.unknown_data().is_some());
        assert_eq!(
            serde_json::to_string(&unknown).unwrap(),
            "\"file.generated\""
        );
    }

    #[test]
    fn test_webhook_state_wire_roundtrip() {
        for (state, wire) in [
            (WebhookState::Enabled, "\"enabled\""),
            (WebhookState::Disabled, "\"disabled\""),
            (
                WebhookState::DisabledDueToFailedDeliveries,
                "\"disabled_due_to_failed_deliveries\"",
            ),
        ] {
            assert_eq!(serde_json::to_string(&state).unwrap(), wire);
            let parsed: WebhookState = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, state);
        }
    }

    #[test]
    fn test_webhook_state_unknown_roundtrip() {
        let unknown: WebhookState = serde_json::from_str("\"paused\"").unwrap();
        assert!(unknown.is_unknown());
        assert_eq!(unknown.unknown_state_type(), Some("paused"));
        assert!(unknown.unknown_data().is_some());
        assert_eq!(serde_json::to_string(&unknown).unwrap(), "\"paused\"");
    }

    #[test]
    fn test_revocation_behavior_wire_roundtrip() {
        for (behavior, wire) in [
            (
                RevocationBehavior::RevokePreviousSecretsAfterH24,
                "\"revoke_previous_secrets_after_h24\"",
            ),
            (
                RevocationBehavior::RevokePreviousSecretsImmediately,
                "\"revoke_previous_secrets_immediately\"",
            ),
        ] {
            assert_eq!(serde_json::to_string(&behavior).unwrap(), wire);
            let parsed: RevocationBehavior = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, behavior);
        }
    }

    #[test]
    fn test_revocation_behavior_unknown_roundtrip() {
        let unknown: RevocationBehavior = serde_json::from_str("\"revoke_after_week\"").unwrap();
        assert!(unknown.is_unknown());
        assert_eq!(unknown.unknown_behavior_type(), Some("revoke_after_week"));
        assert!(unknown.unknown_data().is_some());
        assert_eq!(
            serde_json::to_string(&unknown).unwrap(),
            "\"revoke_after_week\""
        );
    }

    #[test]
    fn test_webhook_new_serializes_input_fields_only() {
        let webhook = Webhook::new(
            "https://example.com/hook",
            vec![WebhookEvent::InteractionCompleted],
        )
        .with_name("my-hook");

        let value = serde_json::to_value(&webhook).unwrap();
        assert_eq!(value["uri"], "https://example.com/hook");
        assert_eq!(value["subscribed_events"][0], "interaction.completed");
        assert_eq!(value["name"], "my-hook");
        // Output-only fields are skipped when unset
        for field in [
            "id",
            "state",
            "signing_secrets",
            "new_signing_secret",
            "create_time",
            "update_time",
        ] {
            assert!(value.get(field).is_none(), "{field} should be skipped");
        }
    }

    #[test]
    fn test_webhook_full_resource_roundtrip() {
        // Wire fixture derived from the generated google-genai bindings.
        let json = json!({
            "id": "webhooks/wh-123",
            "name": "my-hook",
            "uri": "https://example.com/hook",
            "subscribed_events": ["batch.succeeded", "interaction.failed", "video.generated"],
            "state": "enabled",
            "signing_secrets": [
                {"truncated_secret": "whsec_...abcd", "expire_time": "2026-08-01T00:00:00Z"}
            ],
            "new_signing_secret": "whsec_full_secret",
            "create_time": "2026-07-01T12:00:00Z",
            "update_time": "2026-07-02T12:00:00Z"
        });

        let webhook: Webhook = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(webhook.id.as_deref(), Some("webhooks/wh-123"));
        assert_eq!(webhook.state, Some(WebhookState::Enabled));
        assert_eq!(webhook.subscribed_events.len(), 3);
        assert_eq!(
            webhook.signing_secrets.as_ref().unwrap()[0]
                .truncated_secret
                .as_deref(),
            Some("whsec_...abcd")
        );

        let back = serde_json::to_value(&webhook).unwrap();
        assert_eq!(back, json);
    }

    #[test]
    fn test_webhook_update_partial_serialization() {
        let update = WebhookUpdate::new().with_state(WebhookState::Disabled);
        let value = serde_json::to_value(&update).unwrap();
        assert_eq!(value, json!({"state": "disabled"}));
    }

    #[test]
    fn test_webhook_list_response_deserialization() {
        let json = json!({
            "webhooks": [
                {"uri": "https://a.example.com", "subscribed_events": ["batch.failed"]}
            ],
            "next_page_token": "tok-1"
        });
        let list: WebhookListResponse = serde_json::from_value(json).unwrap();
        assert_eq!(list.webhooks.len(), 1);
        assert_eq!(list.next_page_token.as_deref(), Some("tok-1"));

        // Empty response is valid too
        let empty: WebhookListResponse = serde_json::from_str("{}").unwrap();
        assert!(empty.webhooks.is_empty());
        assert!(empty.next_page_token.is_none());
    }

    #[test]
    fn test_rotate_signing_secret_response() {
        let response: RotateSigningSecretResponse =
            serde_json::from_str(r#"{"secret": "whsec_new"}"#).unwrap();
        assert_eq!(response.secret.as_deref(), Some("whsec_new"));

        let empty: RotateSigningSecretResponse = serde_json::from_str("{}").unwrap();
        assert!(empty.secret.is_none());
    }

    #[test]
    fn test_webhook_debug_redacts_new_signing_secret() {
        let webhook = Webhook {
            new_signing_secret: Some("whsec_super_secret".to_string()),
            ..Webhook::new("https://example.com/hook", vec![])
        };
        let debug = format!("{webhook:?}");
        assert!(!debug.contains("whsec_super_secret"));
        assert!(debug.contains("[REDACTED]"));
        // Absent secrets print as None (no misleading placeholder).
        let no_secret = Webhook::new("https://example.com/hook", vec![]);
        assert!(!format!("{no_secret:?}").contains("[REDACTED]"));
    }

    #[test]
    fn test_rotate_signing_secret_response_debug_redacts_secret() {
        let response = RotateSigningSecretResponse {
            secret: Some("whsec_rotated_secret".to_string()),
        };
        let debug = format!("{response:?}");
        assert!(!debug.contains("whsec_rotated_secret"));
        assert!(debug.contains("[REDACTED]"));
    }

    #[test]
    fn test_webhook_config_serialization() {
        let config = WebhookConfig::new()
            .with_uris(vec!["https://example.com/hook".to_string()])
            .with_user_metadata(json!({"job": "nightly"}));

        let value = serde_json::to_value(&config).unwrap();
        assert_eq!(
            value,
            json!({
                "uris": ["https://example.com/hook"],
                "user_metadata": {"job": "nightly"}
            })
        );
    }

    #[test]
    fn test_webhook_config_empty_serializes_to_empty_object() {
        let config = WebhookConfig::new();
        assert_eq!(serde_json::to_string(&config).unwrap(), "{}");
    }

    #[test]
    fn test_webhook_config_roundtrip() {
        let config = WebhookConfig::new()
            .with_uris(vec!["https://example.com/a".to_string()])
            .with_user_metadata(json!({"k": [1, 2, 3]}));
        let json = serde_json::to_string(&config).unwrap();
        let parsed: WebhookConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, parsed);
    }

    #[test]
    fn test_webhook_event_display() {
        assert_eq!(
            WebhookEvent::InteractionCompleted.to_string(),
            "interaction.completed"
        );
        let unknown = WebhookEvent::Unknown {
            event_type: "x.y".to_string(),
            data: json!("x.y"),
        };
        assert_eq!(unknown.to_string(), "x.y");
    }
}