coralogix-cli 0.1.38

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
use std::collections::HashMap;

use anyhow::anyhow;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use serde::Deserialize;
use serde_json::Value;

use crate::api_client::CxClient;
use crate::error::Result;

// --- Response types ---

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Case {
    pub id: Option<String>,
    pub readable_id: Option<String>,
    pub title: Option<String>,
    pub status: Option<String>,
    pub priority: Option<String>,
    pub priority_details: Option<PriorityDetails>,
    pub category: Option<String>,
    pub assignee: Option<UserDetails>,
    pub create_time: Option<String>,
    pub update_time: Option<String>,
    pub acknowledge_time: Option<String>,
    pub resolution_details: Option<Value>,
    pub duration: Option<Value>,
    pub ai_summary: Option<String>,
    #[serde(default)]
    pub labels: Vec<KeyValue>,
    #[serde(default)]
    pub groupings: Vec<KeyValue>,
    #[serde(default)]
    pub impacted_entities: Vec<Value>,
    pub kpi_breaches: Option<Value>,
    pub case_indicators: Option<Value>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserDetails {
    pub user_id: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PriorityDetails {
    pub system: Option<String>,
    pub r#override: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct KeyValue {
    pub key: Option<String>,
    pub value: Option<String>,
}

impl Case {
    /// Strip "CASE_STATUS_" prefix → "ACTIVE".
    pub fn display_status(&self) -> String {
        self.status
            .as_deref()
            .map(|s| s.strip_prefix("CASE_STATUS_").unwrap_or(s).to_string())
            .unwrap_or_else(|| "-".to_string())
    }

    /// Strip "CASE_PRIORITY_" prefix → "P1".
    pub fn display_priority(&self) -> String {
        self.priority
            .as_deref()
            .map(|s| s.strip_prefix("CASE_PRIORITY_").unwrap_or(s).to_string())
            .unwrap_or_else(|| "-".to_string())
    }

    /// Strip "CASE_CATEGORY_" prefix → "AVAILABILITY".
    pub fn display_category(&self) -> String {
        self.category
            .as_deref()
            .map(|s| s.strip_prefix("CASE_CATEGORY_").unwrap_or(s).to_string())
            .unwrap_or_else(|| "-".to_string())
    }

    pub fn display_assignee(&self) -> String {
        self.assignee
            .as_ref()
            .and_then(|a| a.user_id.clone())
            .unwrap_or_else(|| "-".to_string())
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListEventsResponse {
    #[serde(default)]
    pub events: Vec<Value>,
}

/// One user row from the team users search endpoint
/// `GET /mgmt/openapi/5/aaa/teams/v2/{team_id}/search`. Only the fields we use
/// are modeled; the endpoint also returns firstName/lastName/status etc.
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TeamUser {
    /// Opaque user ID (UUID). Matches a case's `assignee.userId`.
    pub user_id: Option<String>,
    /// The user's email address (the API field is named `username`).
    pub username: Option<String>,
}

#[derive(Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SearchUsersResponse {
    #[serde(default)]
    pub users: Vec<TeamUser>,
    /// Offset token for the next page; absent once the last page is reached.
    pub next_page_token: Option<i64>,
}

/// In-memory lookup over the team-members list, used to convert between
/// opaque user IDs (the API's currency) and email addresses (what humans
/// recognize). Built once per command invocation per profile.
#[derive(Debug, Default, Clone)]
pub struct TeammateDirectory {
    by_id: HashMap<String, String>,
    by_email: HashMap<String, String>,
}

impl TeammateDirectory {
    pub fn from_users(users: Vec<TeamUser>) -> Self {
        let mut by_id = HashMap::new();
        let mut by_email = HashMap::new();
        for u in users {
            if let (Some(id), Some(email)) = (u.user_id, u.username) {
                by_id.insert(id.clone(), email.clone());
                by_email.insert(email.to_lowercase(), id);
            }
        }
        Self { by_id, by_email }
    }

    pub fn email_for(&self, user_id: &str) -> Option<&str> {
        self.by_id.get(user_id).map(String::as_str)
    }

    pub fn user_id_for_email(&self, email: &str) -> Option<&str> {
        self.by_email.get(&email.to_lowercase()).map(String::as_str)
    }

    /// Resolve user input (which may be an email or a raw user ID) to a user ID.
    ///
    /// Inputs containing `@` are treated as emails and must be found in the
    /// directory or an error is returned. Other inputs are passed through
    /// unchanged on the assumption that they are already a user ID — the
    /// server will reject malformed values.
    pub fn resolve_to_user_id(&self, input: &str) -> anyhow::Result<String> {
        if input.contains('@') {
            self.user_id_for_email(input)
                .map(String::from)
                .ok_or_else(|| {
                    anyhow!(
                        "no team member found with email '{input}'. \
                         Run `cx iam users search` (or check `cx cases get <id>`) for the right address."
                    )
                })
        } else {
            Ok(input.to_string())
        }
    }
}

// --- API client ---

const CASES_BASE: &str = "/mgmt/openapi/5/cases/cases/v1";
const CASES_CREATE: &str = "/mgmt/openapi/5/cases/cases/create/v1";
const EVENTS_BASE: &str = "/mgmt/openapi/5/cases/events/v1";
const PRIORITY_BASE: &str = "/mgmt/openapi/5/cases/priority-override/v1";
const ASSIGNED_BASE: &str = "/mgmt/openapi/5/cases/assigned/v1";
const ACKNOWLEDGED_BASE: &str = "/mgmt/openapi/5/cases/acknowledged/v1";
const CLOSED_BASE: &str = "/mgmt/openapi/5/cases/closed/v1";
const RESOLVED_BASE: &str = "/mgmt/openapi/5/cases/resolved/v1";
const MUTED_BASE: &str = "/mgmt/openapi/5/cases/muted/v1";
/// `linkAs` value that makes the case in the path the child of `targetCaseId`.
const LINK_AS_CHILD: &str = "LINKED_CASE_RELATIONSHIP_CHILD";
const NOTIFICATION_DELIVERIES_BASE: &str = "/mgmt/openapi/5/cases/notifications/v1/deliveries";
const USERS_BASE: &str = "/mgmt/openapi/5/aaa/teams/v2";
/// Page size for the paginated team-users search. The endpoint caps how many
/// rows it returns per call, so we walk pages until `nextPageToken` is absent.
const USERS_PAGE_SIZE: i64 = 300;

/// Case and event ids come from user (or agent) input and travel as one URL
/// path segment, so encode everything except RFC 3986 unreserved characters.
/// Without this, an id such as `x/../y` would rewrite the request path.
const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'~');

fn path_segment(id: &str) -> String {
    utf8_percent_encode(id, PATH_SEGMENT_ENCODE_SET).to_string()
}

pub struct CasesApi<'a> {
    client: &'a CxClient,
}

impl<'a> CasesApi<'a> {
    pub fn new(client: &'a CxClient) -> Self {
        Self { client }
    }

    /// Get a single case by ID.
    pub async fn get(&self, id: &str) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}", path_segment(id));
        self.client.get(&path, &[]).await
    }

    pub async fn deep_links(&self, id: &str) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}/deep-links", path_segment(id));
        self.client.get(&path, &[]).await
    }

    /// Create a case manually. The body is a `CreateCaseRequest` (title,
    /// priority, and optional description, labels, assignee, status); the
    /// created case is not linked to any indicator.
    pub async fn create(&self, body: &Value) -> Result<Value> {
        self.client.post(CASES_CREATE, body).await
    }

    /// Update a case (partial patch). The endpoint takes the updatable fields
    /// directly as the request body — it has no `patch` wrapper field.
    pub async fn update(&self, id: &str, patch: &Value) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}", path_segment(id));
        self.client.put(&path, patch).await
    }

    /// Assign a case to a user.
    pub async fn assign(&self, id: &str, user_id: &str) -> Result<Value> {
        let path = format!("{ASSIGNED_BASE}/{}", path_segment(id));
        let body = serde_json::json!({ "assignee": { "userId": user_id } });
        self.client.post(&path, &body).await
    }

    /// Remove the assignee from a case.
    pub async fn unassign(&self, id: &str) -> Result<Value> {
        let path = format!("{ASSIGNED_BASE}/{}", path_segment(id));
        self.client.delete(&path).await
    }

    /// Acknowledge a case.
    pub async fn acknowledge(&self, id: &str) -> Result<Value> {
        let path = format!("{ACKNOWLEDGED_BASE}/{}", path_segment(id));
        let body = serde_json::json!({});
        self.client.put(&path, &body).await
    }

    /// Remove the acknowledgment from a case.
    pub async fn unacknowledge(&self, id: &str) -> Result<Value> {
        let path = format!("{ACKNOWLEDGED_BASE}/{}", path_segment(id));
        self.client.delete(&path).await
    }

    /// Close a case.
    pub async fn close(&self, id: &str) -> Result<Value> {
        let path = format!("{CLOSED_BASE}/{}", path_segment(id));
        let body = serde_json::json!({});
        self.client.post(&path, &body).await
    }

    /// Resolve a case with an optional reason.
    pub async fn resolve(&self, id: &str, reason: Option<&str>) -> Result<Value> {
        let path = format!("{RESOLVED_BASE}/{}", path_segment(id));
        let mut body = serde_json::Map::new();
        if let Some(r) = reason {
            body.insert("reason".to_string(), Value::String(r.to_string()));
        }
        self.client.put(&path, &Value::Object(body)).await
    }

    /// Override a case's priority.
    pub async fn set_priority(&self, id: &str, priority: &str) -> Result<Value> {
        let path = format!("{PRIORITY_BASE}/{}", path_segment(id));
        let body = serde_json::json!({ "priority": priority });
        self.client.put(&path, &body).await
    }

    /// Clear a case's priority override.
    pub async fn clear_priority(&self, id: &str) -> Result<Value> {
        let path = format!("{PRIORITY_BASE}/{}", path_segment(id));
        self.client.delete(&path).await
    }

    /// Mute a case so it stops sending notifications. Its status is unchanged.
    pub async fn mute(&self, id: &str) -> Result<Value> {
        let path = format!("{MUTED_BASE}/{}", path_segment(id));
        self.client
            .put_or_empty(&path, &serde_json::json!({}))
            .await
    }

    /// Restore notifications for a muted case.
    pub async fn unmute(&self, id: &str) -> Result<Value> {
        let path = format!("{MUTED_BASE}/{}", path_segment(id));
        self.client.delete(&path).await
    }

    /// Read a case's parent or children.
    pub async fn list_linked(&self, id: &str) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}/linked-cases", path_segment(id));
        self.client.get(&path, &[]).await
    }

    /// Make `child_id` a child of `parent_uuid`. The link endpoint takes the
    /// parent only as a UUID.
    pub async fn set_parent(
        &self,
        child_id: &str,
        parent_uuid: &str,
        mute_child: bool,
    ) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}/linked-cases", path_segment(child_id));
        let body = serde_json::json!({
            "targetCaseId": parent_uuid,
            "linkAs": LINK_AS_CHILD,
            "muteChild": mute_child,
        });
        self.client.post_or_empty(&path, &body).await
    }

    /// Remove the parent-child link between `id` and `linked_uuid`.
    pub async fn unlink(&self, id: &str, linked_uuid: &str) -> Result<Value> {
        let path = format!(
            "{CASES_BASE}/{}/linked-cases/{}",
            path_segment(id),
            path_segment(linked_uuid)
        );
        self.client.delete(&path).await
    }

    /// Resolve a case reference (UUID or readable ID such as CASE-123) to its
    /// UUID, for the endpoints that accept only UUIDs.
    pub async fn resolve_case_uuid(&self, id: &str) -> Result<String> {
        let trimmed = id.trim();
        if uuid::Uuid::parse_str(trimmed).is_ok() {
            return Ok(trimmed.to_string());
        }
        let case: Value = self.get(trimmed).await?;
        case.get("case")
            .and_then(|c| c.get("id"))
            .and_then(Value::as_str)
            .map(String::from)
            .ok_or_else(|| crate::error::CxError::Api {
                status: 0,
                message: format!("case '{trimmed}' has no id in the API response"),
            })
    }

    /// List events for a case.
    pub async fn list_events(
        &self,
        case_id: &str,
        include_children: bool,
    ) -> Result<ListEventsResponse> {
        let path = format!("{CASES_BASE}/{}/events", path_segment(case_id));
        let params: &[(&str, &str)] = if include_children {
            &[("includeChildrenEvents", "true")]
        } else {
            &[]
        };
        self.client.get(&path, params).await
    }

    /// Add a comment to a case. The body field is `text`; the server stores it
    /// as a comment event (`eventData.comment.unsafeText`) and returns the
    /// created event.
    pub async fn create_comment(&self, case_id: &str, text: &str) -> Result<Value> {
        let path = format!("{CASES_BASE}/{}/comments", path_segment(case_id));
        let body = serde_json::json!({ "text": text });
        self.client.post(&path, &body).await
    }

    /// Get a single case event by event ID.
    pub async fn get_event(&self, event_id: &str) -> Result<Value> {
        let path = format!("{EVENTS_BASE}/{}", path_segment(event_id));
        self.client.get(&path, &[]).await
    }

    /// List notification deliveries for one or more cases. The endpoint accepts
    /// both readable IDs (e.g. "CASE-764019") and UUIDs in `caseIds`, and keys
    /// the `deliveriesByCase` response under whatever form was passed.
    pub async fn list_notification_deliveries(&self, case_ids: &[String]) -> Result<Value> {
        let body = serde_json::json!({ "caseIds": case_ids });
        self.client.post(NOTIFICATION_DELIVERIES_BASE, &body).await
    }

    /// List all team members by walking the paginated team-users search
    /// endpoint (`GET /mgmt/openapi/5/aaa/teams/v2/{team_id}/search`) in pages
    /// of [`USERS_PAGE_SIZE`], following `nextPageToken` until it is absent.
    pub async fn list_teammates(&self) -> Result<Vec<TeamUser>> {
        let team_id = crate::identity::resolve_team_id(self.client)
            .await
            .map_err(|e| crate::error::CxError::Api {
                status: 0,
                message: e.to_string(),
            })?;
        let path = format!("{USERS_BASE}/{team_id}/search");
        let page_size = USERS_PAGE_SIZE.to_string();

        let mut users = Vec::new();
        let mut page_token: Option<String> = None;
        loop {
            let mut params: Vec<(&str, &str)> = vec![("pageSize", page_size.as_str())];
            if let Some(ref token) = page_token {
                params.push(("pageToken", token.as_str()));
            }
            let resp: SearchUsersResponse = self.client.get(&path, &params).await?;
            let page_len = resp.users.len();
            users.extend(resp.users);
            // Stop once the server reports no further page, or returns an empty
            // page (defensive: avoids looping if a token is ever echoed back).
            match resp.next_page_token {
                Some(token) if page_len > 0 => page_token = Some(token.to_string()),
                _ => break,
            }
        }
        Ok(users)
    }

    /// Convenience: fetch teammates and build a [`TeammateDirectory`].
    /// Errors are surfaced; callers that want best-effort behavior should
    /// `.unwrap_or_default()`.
    pub async fn teammate_directory(&self) -> Result<TeammateDirectory> {
        let users = self.list_teammates().await?;
        Ok(TeammateDirectory::from_users(users))
    }
}

// --- Tests ---

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

    #[test]
    fn path_segment_keeps_ids_in_one_segment() {
        assert_eq!(path_segment("CASE-383"), "CASE-383");
        assert_eq!(
            path_segment("0b7c1f2e-9a4d-4c1e-8f00-123456789abc"),
            "0b7c1f2e-9a4d-4c1e-8f00-123456789abc"
        );
        assert_eq!(path_segment("bad id/../x"), "bad%20id%2F..%2Fx");
        assert_eq!(path_segment("a?b#c"), "a%3Fb%23c");
    }
    use serde_json::json;

    #[test]
    fn deserialize_case() {
        let unassigned: Case = serde_json::from_value(json!({
            "id": "3f166e9f-3c88-4af2-b52e-138f339dab3e",
            "readableId": "CASE-123",
            "title": "Database outage investigation",
            "status": "CASE_STATUS_ACTIVE",
            "priority": "CASE_PRIORITY_P2",
            "category": "CASE_CATEGORY_AVAILABILITY",
            "createTime": "2025-09-22T10:30:00Z"
        }))
        .unwrap();
        assert_eq!(unassigned.display_status(), "ACTIVE");
        assert_eq!(unassigned.display_priority(), "P2");
        assert_eq!(unassigned.display_category(), "AVAILABILITY");
        assert_eq!(unassigned.display_assignee(), "-");

        let assigned: Case = serde_json::from_value(json!({
            "id": "a4c7d2e8-5f99-4b3a-c53f-239f440dbe4f",
            "title": "Security incident",
            "status": "CASE_STATUS_ACKNOWLEDGED",
            "priority": "CASE_PRIORITY_P1",
            "category": "CASE_CATEGORY_SECURITY",
            "createTime": "2025-09-23T09:00:00Z",
            "assignee": { "userId": "user-1" }
        }))
        .unwrap();
        assert_eq!(assigned.display_status(), "ACKNOWLEDGED");
        assert_eq!(assigned.display_assignee(), "user-1");
    }

    #[test]
    fn display_missing_fields() {
        let case = Case {
            id: None,
            readable_id: None,
            title: None,
            status: None,
            priority: None,
            priority_details: None,
            category: None,
            assignee: None,
            create_time: None,
            update_time: None,
            acknowledge_time: None,
            resolution_details: None,
            duration: None,
            ai_summary: None,
            labels: vec![],
            groupings: vec![],
            impacted_entities: vec![],
            kpi_breaches: None,
            case_indicators: None,
        };
        assert_eq!(case.display_status(), "-");
        assert_eq!(case.display_priority(), "-");
        assert_eq!(case.display_category(), "-");
        assert_eq!(case.display_assignee(), "-");
    }

    #[test]
    fn deserialize_priority_details() {
        let body = json!({
            "system": "CASE_PRIORITY_P2",
            "override": "CASE_PRIORITY_P1"
        });
        let pd: PriorityDetails = serde_json::from_value(body).unwrap();
        assert_eq!(pd.system.as_deref(), Some("CASE_PRIORITY_P2"));
        assert_eq!(pd.r#override.as_deref(), Some("CASE_PRIORITY_P1"));
    }

    #[test]
    fn deserialize_events_response() {
        let body = json!({
            "events": [
                {
                    "id": "f56645c5-9cd4-4b9f-961f-4f852d8835a0",
                    "type": "EVENT_TYPE_COMMENT",
                    "createTime": "2025-09-22T11:00:00Z"
                },
                {
                    "id": "0a08c310-ae44-6009-28ec-b6b7da50a99c",
                    "type": "EVENT_TYPE_STATUS_CHANGE"
                }
            ]
        });
        let resp: ListEventsResponse = serde_json::from_value(body).unwrap();
        assert_eq!(resp.events.len(), 2);
        assert_eq!(
            resp.events[0]["id"].as_str(),
            Some("f56645c5-9cd4-4b9f-961f-4f852d8835a0")
        );
    }

    #[test]
    fn deserialize_events_response_empty() {
        let resp: ListEventsResponse = serde_json::from_value(json!({})).unwrap();
        assert!(resp.events.is_empty());
    }

    #[test]
    fn deserialize_search_users_response() {
        let body = json!({
            "users": [
                {
                    "userId": "281da03a-0241-447e-aca0-f90083b8198a",
                    "userAccountId": 44584,
                    "status": "USER_STATUS_ACTIVE",
                    "username": "Alessandro.Massa@coralogix.com",
                    "firstName": "Alessandro",
                    "lastName": "Massa"
                },
                {
                    "userId": "60291e28-3bec-4bb4-b7e5-3deabcdc80d2",
                    "username": "ilia.shurygin@coralogix.com"
                }
            ],
            "nextPageToken": 2,
            "totalCount": 2
        });
        let resp: SearchUsersResponse = serde_json::from_value(body).unwrap();
        assert_eq!(resp.users.len(), 2);
        assert_eq!(
            resp.users[0].username.as_deref(),
            Some("Alessandro.Massa@coralogix.com")
        );
        assert_eq!(resp.next_page_token, Some(2));
    }

    #[test]
    fn deserialize_search_users_last_page() {
        // The last page omits `nextPageToken`.
        let body = json!({ "users": [], "totalCount": 0 });
        let resp: SearchUsersResponse = serde_json::from_value(body).unwrap();
        assert!(resp.users.is_empty());
        assert_eq!(resp.next_page_token, None);
    }

    #[test]
    fn directory_round_trips_id_and_email() {
        let dir = TeammateDirectory::from_users(vec![
            TeamUser {
                user_id: Some("uid-1".into()),
                username: Some("alice@example.com".into()),
            },
            TeamUser {
                user_id: Some("uid-2".into()),
                username: Some("Bob@Example.com".into()),
            },
        ]);

        assert_eq!(dir.email_for("uid-1"), Some("alice@example.com"));
        assert_eq!(dir.email_for("uid-2"), Some("Bob@Example.com"));
        assert_eq!(dir.email_for("nope"), None);

        // Lookup is case-insensitive on the email side.
        assert_eq!(dir.user_id_for_email("alice@example.com"), Some("uid-1"));
        assert_eq!(dir.user_id_for_email("ALICE@example.com"), Some("uid-1"));
        assert_eq!(dir.user_id_for_email("bob@example.com"), Some("uid-2"));
    }

    #[test]
    fn directory_resolve_email_to_id() {
        let dir = TeammateDirectory::from_users(vec![TeamUser {
            user_id: Some("uid-1".into()),
            username: Some("alice@example.com".into()),
        }]);

        assert_eq!(
            dir.resolve_to_user_id("alice@example.com").unwrap(),
            "uid-1"
        );
        // Non-email input passes through unchanged.
        assert_eq!(dir.resolve_to_user_id("uid-1").unwrap(), "uid-1");
        assert_eq!(dir.resolve_to_user_id("some-uuid").unwrap(), "some-uuid");
        // Unknown email errors out.
        let err = dir.resolve_to_user_id("ghost@example.com").unwrap_err();
        assert!(err.to_string().contains("no team member found"));
    }

    #[test]
    fn deserialize_labels_and_groupings() {
        let case: Case = serde_json::from_value(json!({
            "title": "x",
            "labels": [{ "key": "team", "value": "backend" }],
            "groupings": [{ "key": "service", "value": "payments" }]
        }))
        .unwrap();
        assert_eq!(case.labels.len(), 1);
        assert_eq!(case.labels[0].key.as_deref(), Some("team"));
        assert_eq!(case.groupings[0].value.as_deref(), Some("payments"));
    }
}