bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
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
//! Client and types for **Bytebury Monitors** (`https://api.bytebury.com/monitors/v1`).
//!
//! Create and manage HTTP uptime monitors, run on-demand checks, inspect 90-day
//! uptime summaries, publish and update status-page incidents, and manage
//! dead-man's-switch heartbeats.

use std::collections::BTreeMap;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;
use crate::pagination::{Page, PageParams};

const PRODUCT: &str = "monitors";
const MANUAL_CHECK_TIMEOUT: Duration = Duration::from_secs(45);

/// Client for **Bytebury Monitors**.
///
/// Obtained via [`Bibby::monitors`].
#[derive(Debug, Clone, Copy)]
pub struct MonitorsClient<'a> {
    client: &'a Bibby,
}

impl<'a> MonitorsClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Lists uptime monitors in your account.
    ///
    /// Calls `GET /monitors/v1/monitors`.
    pub async fn list(&self, params: &ListMonitorsParams) -> Result<Page<Monitor>> {
        self.client
            .get_json_query(PRODUCT, "monitors", params)
            .await
    }

    /// Creates a new HTTP uptime monitor.
    ///
    /// Calls `POST /monitors/v1/monitors`.
    pub async fn create(&self, request: &CreateMonitorRequest) -> Result<Monitor> {
        self.client.post_json(PRODUCT, "monitors", request).await
    }

    /// Fetches a monitor by ID.
    ///
    /// Calls `GET /monitors/v1/monitors/{id}`.
    pub async fn get(&self, id: i64) -> Result<Monitor> {
        self.client
            .get_json(PRODUCT, &format!("monitors/{id}"))
            .await
    }

    /// Updates a monitor's configuration or pauses/resumes it.
    ///
    /// Calls `PATCH /monitors/v1/monitors/{id}`.
    pub async fn update(&self, id: i64, changes: &UpdateMonitorRequest) -> Result<Monitor> {
        self.client
            .patch_json(PRODUCT, &format!("monitors/{id}"), changes)
            .await
    }

    /// Permanently deletes a monitor.
    ///
    /// Calls `DELETE /monitors/v1/monitors/{id}`.
    pub async fn delete(&self, id: i64) -> Result<DeletedMonitor> {
        self.client
            .delete_json(PRODUCT, &format!("monitors/{id}"))
            .await
    }

    /// Runs an immediate on-demand check for a monitor.
    ///
    /// Calls `POST /monitors/v1/monitors/{id}/check`.
    pub async fn check_now(&self, id: i64) -> Result<Check> {
        self.client
            .post_empty_with_timeout(
                PRODUCT,
                &format!("monitors/{id}/check"),
                MANUAL_CHECK_TIMEOUT,
            )
            .await
    }

    /// Lists recent check results for a monitor (newest first).
    ///
    /// Calls `GET /monitors/v1/monitors/{id}/checks`.
    pub async fn list_checks(&self, id: i64, params: &PageParams) -> Result<Page<Check>> {
        self.client
            .get_json_query(PRODUCT, &format!("monitors/{id}/checks"), params)
            .await
    }

    /// Returns an overall uptime status summary across all monitors and recent incidents.
    ///
    /// `days` may be `1..=90` (defaults to `30`).
    ///
    /// Calls `GET /monitors/v1/status`.
    pub async fn status(&self, days: Option<i64>) -> Result<StatusSummary> {
        #[derive(Serialize)]
        struct Query {
            #[serde(skip_serializing_if = "Option::is_none")]
            days: Option<i64>,
        }
        self.client
            .get_json_query(PRODUCT, "status", &Query { days })
            .await
    }

    /// Lists incidents (optionally filtered to open or resolved).
    ///
    /// Calls `GET /monitors/v1/incidents`.
    pub async fn list_incidents(&self, params: &ListIncidentsParams) -> Result<Page<Incident>> {
        self.client
            .get_json_query(PRODUCT, "incidents", params)
            .await
    }

    /// Creates a new incident (and posts it to your status page).
    ///
    /// Calls `POST /monitors/v1/incidents`.
    pub async fn create_incident(&self, request: &CreateIncidentRequest) -> Result<Incident> {
        self.client.post_json(PRODUCT, "incidents", request).await
    }

    /// Updates an incident and/or appends a timeline update.
    ///
    /// Calls `PATCH /monitors/v1/incidents/{id}`.
    pub async fn update_incident(
        &self,
        id: i64,
        changes: &UpdateIncidentRequest,
    ) -> Result<Incident> {
        self.client
            .patch_json(PRODUCT, &format!("incidents/{id}"), changes)
            .await
    }

    /// Edits an existing timeline update on an incident.
    ///
    /// Calls `PATCH /monitors/v1/incidents/{incident_id}/updates/{update_id}`.
    pub async fn edit_incident_update(
        &self,
        incident_id: i64,
        update_id: i64,
        request: &EditIncidentUpdateRequest,
    ) -> Result<Incident> {
        self.client
            .patch_json(
                PRODUCT,
                &format!("incidents/{incident_id}/updates/{update_id}"),
                request,
            )
            .await
    }

    /// Deletes a timeline update from an incident.
    ///
    /// Calls `DELETE /monitors/v1/incidents/{incident_id}/updates/{update_id}`.
    pub async fn delete_incident_update(
        &self,
        incident_id: i64,
        update_id: i64,
    ) -> Result<Incident> {
        self.client
            .delete_json(
                PRODUCT,
                &format!("incidents/{incident_id}/updates/{update_id}"),
            )
            .await
    }

    /// Lists dead-man's-switch heartbeat monitors.
    ///
    /// Calls `GET /monitors/v1/heartbeats`.
    pub async fn list_heartbeats(&self) -> Result<Vec<Heartbeat>> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum HeartbeatList {
            Direct(Vec<Heartbeat>),
            Wrapped { data: Vec<Heartbeat> },
        }
        let resp: HeartbeatList = self.client.get_json(PRODUCT, "heartbeats").await?;
        Ok(match resp {
            HeartbeatList::Direct(items) => items,
            HeartbeatList::Wrapped { data } => data,
        })
    }

    /// Creates a new dead-man's-switch heartbeat monitor.
    ///
    /// Calls `POST /monitors/v1/heartbeats`.
    pub async fn create_heartbeat(&self, request: &CreateHeartbeatRequest) -> Result<Heartbeat> {
        self.client.post_json(PRODUCT, "heartbeats", request).await
    }

    /// Deletes a heartbeat monitor.
    ///
    /// Calls `DELETE /monitors/v1/heartbeats/{id}`.
    pub async fn delete_heartbeat(&self, id: i64) -> Result<()> {
        self.client
            .delete_unit(PRODUCT, &format!("heartbeats/{id}"))
            .await
    }
}

/// HTTP method supported by uptime monitors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MonitorMethod {
    /// `GET`
    Get,
    /// `HEAD`
    Head,
    /// `POST`
    Post,
}

/// Current health state of a monitor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MonitorStatus {
    /// Not yet checked.
    Unknown,
    /// Target is healthy.
    Up,
    /// Target is failing checks.
    Down,
}

/// Aggregate health across all monitors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OverallStatus {
    /// All monitors operational.
    Operational,
    /// Partial degradation.
    Degraded,
    /// Active outage.
    Outage,
}

/// How a check was initiated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckTrigger {
    /// Periodic background check.
    Schedule,
    /// Manual on-demand check.
    Manual,
}

/// Incident lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IncidentStatus {
    /// Team is investigating.
    Investigating,
    /// Root cause identified.
    Identified,
    /// Fix deployed and monitoring recovery.
    Monitoring,
    /// Incident resolved.
    Resolved,
}

/// Incident severity level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IncidentSeverity {
    /// Minor impact.
    Minor,
    /// Major impact.
    Major,
    /// Critical outage.
    Critical,
    /// Planned maintenance window.
    Maintenance,
}

/// Query parameters for [`MonitorsClient::list`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListMonitorsParams {
    /// Case-insensitive substring filter on name or URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    /// Filter by enabled (`true`) or paused (`false`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `25`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// Request body for [`MonitorsClient::create`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateMonitorRequest {
    /// Display name (max 120 bytes).
    pub name: String,
    /// Public `http://` or `https://` URL to monitor.
    pub url: String,
    /// HTTP method (`GET`, `HEAD`, or `POST`; default `GET`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<MonitorMethod>,
    /// Optional HTTP headers (max 20; supports [`crate::vault_ref!`] placeholders).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Expected HTTP status (`100..=599`, or `0` for any 2xx; default `200`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_status: Option<i32>,
    /// Check interval in seconds (default `300`; min `60` on paid plans).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_seconds: Option<i32>,
    /// Request timeout in seconds (`1..=30`, default `10`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<i32>,
    /// Whether the monitor starts active (default `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Whether outage alerts are sent (default `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notify: Option<bool>,
}

impl CreateMonitorRequest {
    /// Creates a new monitor request with required `name` and `url`.
    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: url.into(),
            method: None,
            headers: None,
            expected_status: None,
            interval_seconds: None,
            timeout_seconds: None,
            enabled: None,
            notify: None,
        }
    }

    /// Sets the HTTP method.
    pub fn method(mut self, method: MonitorMethod) -> Self {
        self.method = Some(method);
        self
    }

    /// Sets custom HTTP headers.
    pub fn headers(mut self, headers: BTreeMap<String, String>) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Sets the expected HTTP status code (`0` accepts any `2xx`).
    pub fn expected_status(mut self, status: i32) -> Self {
        self.expected_status = Some(status);
        self
    }

    /// Sets the check interval in seconds.
    pub fn interval_seconds(mut self, seconds: i32) -> Self {
        self.interval_seconds = Some(seconds);
        self
    }
}

/// Request body for [`MonitorsClient::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateMonitorRequest {
    /// Updated name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Updated URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Updated method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<MonitorMethod>,
    /// Replaces custom headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Updated expected status code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_status: Option<i32>,
    /// Updated check interval in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_seconds: Option<i32>,
    /// Updated timeout in seconds (`1..=30`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<i32>,
    /// Enable or pause the monitor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Enable or disable alerts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notify: Option<bool>,
}

/// An HTTP uptime monitor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Monitor {
    /// Monitor ID.
    pub id: i64,
    /// Display name.
    pub name: String,
    /// Monitored URL.
    pub url: String,
    /// HTTP method.
    pub method: MonitorMethod,
    /// Custom request headers.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    /// Expected HTTP status (`0` means any 2xx).
    pub expected_status: i32,
    /// Check interval in seconds.
    pub interval_seconds: i32,
    /// Timeout in seconds.
    pub timeout_seconds: i32,
    /// Whether the monitor is active.
    pub enabled: bool,
    /// Whether notifications are enabled.
    pub notify: bool,
    /// Current status (`unknown`, `up`, `down`).
    pub status: MonitorStatus,
    /// Consecutive failed check count.
    pub consecutive_failures: i32,
    /// RFC 3339 timestamp of the last check.
    pub last_checked_at: Option<String>,
    /// RFC 3339 timestamp of the last status transition.
    pub last_status_change_at: Option<String>,
    /// Response latency of the last check in milliseconds.
    pub last_response_ms: Option<i32>,
    /// HTTP status code of the last check.
    pub last_status_code: Option<i32>,
    /// Error from the last check, if any.
    pub last_error: Option<String>,
    /// RFC 3339 timestamp of the next scheduled check.
    pub next_check_at: Option<String>,
    /// RFC 3339 SSL certificate expiry timestamp, if observed.
    #[serde(default)]
    pub ssl_expires_at: Option<String>,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// Response from [`MonitorsClient::delete`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeletedMonitor {
    /// Always `true`.
    pub deleted: bool,
    /// Deleted monitor ID.
    pub id: i64,
}

/// A single uptime check execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Check {
    /// Check ID.
    pub id: i64,
    /// Parent monitor ID.
    pub monitor_id: i64,
    /// Whether this check was scheduled or manual.
    pub trigger: CheckTrigger,
    /// Resulting status (`up` or `down`).
    pub status: MonitorStatus,
    /// HTTP status code received, if any.
    pub status_code: Option<i32>,
    /// Duration in milliseconds.
    pub duration_ms: i32,
    /// Error message, if the check failed.
    pub error: Option<String>,
    /// RFC 3339 check timestamp.
    pub checked_at: String,
}

/// Single-day uptime rollup inside [`MonitorStatusCard`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DailyUptime {
    /// UTC date (`YYYY-MM-DD`).
    pub date: String,
    /// Total checks performed that day.
    pub total_checks: i64,
    /// Checks that succeeded.
    pub up_checks: i64,
    /// Checks that failed.
    pub down_checks: i64,
    /// Uptime percentage (`0.0..=100.0`), if any checks ran.
    pub uptime_percent: Option<f64>,
    /// Average response time in milliseconds, if any checks ran.
    pub avg_response_ms: Option<i32>,
}

/// Per-monitor uptime card inside [`StatusSummary`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MonitorStatusCard {
    /// Monitor ID.
    pub id: i64,
    /// Monitor name.
    pub name: String,
    /// Current status.
    pub status: MonitorStatus,
    /// Timestamp of last check.
    pub last_checked_at: Option<String>,
    /// Response latency of last check in ms.
    pub last_response_ms: Option<i32>,
    /// Error from last check, if any.
    pub last_error: Option<String>,
    /// Aggregate uptime percentage over the requested window.
    pub uptime_percent: Option<f64>,
    /// Aggregate average latency over the requested window.
    pub avg_response_ms: Option<i32>,
    /// Daily uptime breakdown.
    #[serde(default)]
    pub days: Vec<DailyUptime>,
}

/// Response from [`MonitorsClient::status`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StatusSummary {
    /// Aggregate status across all monitors.
    pub overall: OverallStatus,
    /// RFC 3339 timestamp when this summary was computed.
    pub checked_at: String,
    /// Per-monitor status cards.
    #[serde(default)]
    pub monitors: Vec<MonitorStatusCard>,
    /// Up to 25 most recent incidents (open first).
    #[serde(default)]
    pub incidents: Vec<Incident>,
}

/// Query parameters for [`MonitorsClient::list_incidents`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListIncidentsParams {
    /// `Some(true)` for open incidents only, `Some(false)` for resolved only, `None` for all.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open: Option<bool>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `25`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// Request body for [`MonitorsClient::create_incident`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateIncidentRequest {
    /// Incident title (max 160 chars).
    pub title: String,
    /// Optional associated monitor ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub monitor_id: Option<i64>,
    /// Initial status (default `investigating`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<IncidentStatus>,
    /// Incident severity (default `major`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<IncidentSeverity>,
    /// Optional initial timeline message (max 2000 chars).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl CreateIncidentRequest {
    /// Creates a new incident request with the given `title`.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            monitor_id: None,
            status: None,
            severity: None,
            message: None,
        }
    }

    /// Associates the incident with a monitor.
    pub fn monitor_id(mut self, monitor_id: i64) -> Self {
        self.monitor_id = Some(monitor_id);
        self
    }

    /// Sets the initial incident status.
    pub fn status(mut self, status: IncidentStatus) -> Self {
        self.status = Some(status);
        self
    }

    /// Sets the incident severity.
    pub fn severity(mut self, severity: IncidentSeverity) -> Self {
        self.severity = Some(severity);
        self
    }

    /// Sets the initial timeline message.
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

/// Request body for [`MonitorsClient::update_incident`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateIncidentRequest {
    /// Updated title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Updated status (set to `Resolved` to close the incident).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<IncidentStatus>,
    /// Updated severity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<IncidentSeverity>,
    /// New timeline update message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Request body for [`MonitorsClient::edit_incident_update`].
#[derive(Debug, Clone, Serialize)]
pub struct EditIncidentUpdateRequest {
    /// Optional updated status label for this timeline entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<IncidentStatus>,
    /// Updated timeline message (max 2000 chars).
    pub message: String,
}

/// A timeline entry on an [`Incident`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IncidentUpdate {
    /// Timeline entry ID.
    pub id: i64,
    /// Status at the time of this update.
    pub status: IncidentStatus,
    /// Update text.
    pub message: String,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
}

/// A status-page incident.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Incident {
    /// Incident ID.
    pub id: i64,
    /// Associated monitor ID, if any.
    pub monitor_id: Option<i64>,
    /// Associated monitor name, if any.
    pub monitor_name: Option<String>,
    /// Incident title.
    pub title: String,
    /// Current status.
    pub status: IncidentStatus,
    /// Severity tier.
    pub severity: IncidentSeverity,
    /// Latest update message, if any.
    pub message: Option<String>,
    /// Timeline updates (newest first).
    #[serde(default)]
    pub updates: Vec<IncidentUpdate>,
    /// RFC 3339 start timestamp.
    pub started_at: String,
    /// RFC 3339 resolution timestamp, if resolved.
    pub resolved_at: Option<String>,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// Request body for [`MonitorsClient::create_heartbeat`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateHeartbeatRequest {
    /// Heartbeat name.
    pub name: String,
    /// Expected ping interval in seconds.
    pub period_seconds: i32,
    /// Optional grace period in seconds before alerting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grace_seconds: Option<i32>,
}

/// A dead-man's-switch heartbeat monitor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Heartbeat {
    /// Heartbeat ID.
    pub id: i64,
    /// Display name.
    pub name: String,
    /// Ping token (`hb_...`).
    pub token: String,
    /// Expected ping period in seconds.
    pub period_seconds: i32,
    /// Grace window in seconds.
    pub grace_seconds: i32,
    /// Current status string.
    pub status: String,
    /// RFC 3339 timestamp of the most recent ping, if any.
    pub last_ping_at: Option<String>,
}

impl Heartbeat {
    /// Returns the unauthenticated ping URL (`https://bytebury.com/monitors/ping/{token}`).
    pub fn ping_url(&self) -> String {
        format!("https://bytebury.com/monitors/ping/{}", self.token)
    }
}