braze-sync 0.9.2

GitOps CLI for managing Braze configuration as code
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
//! Catalog Schema endpoints. See IMPLEMENTATION.md §8.3.
//!
//! Catalog **items** endpoints (list / upsert / delete items) are not
//! wrapped by this client: braze-sync manages Braze configuration, not
//! runtime data. See docs/scope-boundaries.md.

use crate::braze::error::BrazeApiError;
use crate::braze::BrazeClient;
use crate::resource::{Catalog, CatalogField, CatalogFieldType};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};

/// Wire shape of `GET /catalogs` and `GET /catalogs/{name}` responses.
///
/// **ASSUMED** based on IMPLEMENTATION.md §8.3 and Braze public docs.
/// If the actual shape differs, only this struct and the wrapping
/// logic in this file need to change.
///
/// Fields use serde defaults so an unexpected-but-related shape from
/// Braze (e.g. an extra status field) doesn't break parsing.
#[derive(Debug, Deserialize)]
struct CatalogsResponse {
    #[serde(default)]
    catalogs: Vec<Catalog>,
    /// Pagination cursor returned by Braze when more pages exist.
    /// Its presence is the signal we use to fail closed — see
    /// `list_catalogs`.
    #[serde(default)]
    next_cursor: Option<String>,
}

impl BrazeClient {
    /// `GET /catalogs` — list every catalog schema in the workspace.
    ///
    /// Fails closed on `next_cursor` rather than returning page 1: a
    /// partial view would let `apply` re-create page-2 catalogs and
    /// mis-report drift. Mirrors `list_content_blocks`.
    pub async fn list_catalogs(&self) -> Result<Vec<Catalog>, BrazeApiError> {
        let req = self.get(&["catalogs"]);
        let resp: CatalogsResponse = self.send_json(req).await?;
        if let Some(cursor) = resp.next_cursor.as_deref() {
            if !cursor.is_empty() {
                return Err(BrazeApiError::PaginationNotImplemented {
                    endpoint: "/catalogs",
                    detail: format!(
                        "got {} catalog(s) plus a non-empty next_cursor; \
                         aborting to prevent silent truncation",
                        resp.catalogs.len()
                    ),
                });
            }
        }
        Ok(resp.catalogs)
    }

    /// `GET /catalogs/{name}` — fetch a single catalog schema.
    ///
    /// 404 from Braze and an empty `catalogs` array in the response are
    /// both mapped to [`BrazeApiError::NotFound`] so callers can branch
    /// on "this catalog doesn't exist" without string matching on the
    /// HTTP body.
    pub async fn get_catalog(&self, name: &str) -> Result<Catalog, BrazeApiError> {
        let req = self.get(&["catalogs", name]);
        match self.send_json::<CatalogsResponse>(req).await {
            Ok(resp) => resp
                .catalogs
                .into_iter()
                .next()
                .ok_or_else(|| BrazeApiError::NotFound {
                    resource: format!("catalog '{name}'"),
                }),
            Err(BrazeApiError::Http { status, .. }) if status == StatusCode::NOT_FOUND => {
                Err(BrazeApiError::NotFound {
                    resource: format!("catalog '{name}'"),
                })
            }
            Err(e) => Err(e),
        }
    }

    /// `POST /catalogs` — create a new catalog with its initial schema.
    ///
    /// Normalizes field order before sending: Braze rejects creates whose
    /// first field is not `id` (HTTP 400, `id-not-first-column`), and
    /// on-disk schemas exported from existing workspaces are typically
    /// alphabetized — so a literal `id` field can land mid-array.
    /// `Catalog::normalized()` hoists `id` to position 0.
    ///
    /// Duplicate names surface as `400` with body
    /// `error_id: "catalog-name-already-exists"` per Braze docs and are
    /// propagated to the caller; a subsequent `apply` will see the
    /// existing catalog and no-op on the create.
    pub async fn create_catalog(&self, catalog: &Catalog) -> Result<(), BrazeApiError> {
        let normalized = catalog.normalized();
        let body = CreateCatalogRequest {
            catalogs: vec![CreateCatalogEntry {
                name: &normalized.name,
                description: normalized.description.as_deref(),
                fields: normalized
                    .fields
                    .iter()
                    .map(|f| WireField {
                        name: &f.name,
                        field_type: f.field_type,
                    })
                    .collect(),
            }],
        };
        let req = self.post(&["catalogs"]).json(&body);
        self.send_ok(req).await
    }

    /// `POST /catalogs/{name}/fields` — add one field to a catalog schema.
    ///
    /// **ASSUMED** wire format `{"fields": [{"name": "...", "type": "..."}]}`
    /// per IMPLEMENTATION.md §8.3 + Braze public docs. v0.1.0 sends one
    /// POST per added field.
    pub async fn add_catalog_field(
        &self,
        catalog_name: &str,
        field: &CatalogField,
    ) -> Result<(), BrazeApiError> {
        let body = AddFieldsRequest {
            fields: vec![WireField {
                name: &field.name,
                field_type: field.field_type,
            }],
        };
        let req = self.post(&["catalogs", catalog_name, "fields"]).json(&body);
        self.send_ok(req).await
    }

    /// `DELETE /catalogs/{name}/fields/{field}` — remove a field. **Destructive**.
    ///
    /// 404 from Braze stays as `Http { status: 404, .. }` rather than
    /// being mapped to `NotFound`. The use case is different from
    /// get_catalog: a 404 here means "the field you wanted to delete is
    /// already gone", which is a state-drift signal the user should see
    /// rather than silently no-op. A future `--ignore-missing` flag in
    /// `apply` can opt into idempotent behavior.
    pub async fn delete_catalog_field(
        &self,
        catalog_name: &str,
        field_name: &str,
    ) -> Result<(), BrazeApiError> {
        let req = self.delete(&["catalogs", catalog_name, "fields", field_name]);
        self.send_ok(req).await
    }
}

#[derive(Serialize)]
struct AddFieldsRequest<'a> {
    fields: Vec<WireField<'a>>,
}

#[derive(Serialize)]
struct CreateCatalogRequest<'a> {
    catalogs: Vec<CreateCatalogEntry<'a>>,
}

#[derive(Serialize)]
struct CreateCatalogEntry<'a> {
    name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<&'a str>,
    fields: Vec<WireField<'a>>,
}

#[derive(Serialize)]
struct WireField<'a> {
    name: &'a str,
    /// Reuses the domain type's snake_case `Serialize` impl so the
    /// wire string stays in sync with `CatalogFieldType` automatically.
    #[serde(rename = "type")]
    field_type: CatalogFieldType,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::braze::test_client as make_client;
    use serde_json::json;
    use wiremock::matchers::{body_json, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn list_catalogs_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .and(header("authorization", "Bearer test-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {
                        "name": "cardiology",
                        "description": "Cardiology catalog",
                        "fields": [
                            {"name": "id", "type": "string"},
                            {"name": "score", "type": "number"}
                        ]
                    },
                    {
                        "name": "dermatology",
                        "fields": [
                            {"name": "id", "type": "string"}
                        ]
                    }
                ],
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 2);
        assert_eq!(cats[0].name, "cardiology");
        assert_eq!(cats[0].description.as_deref(), Some("Cardiology catalog"));
        assert_eq!(cats[0].fields.len(), 2);
        assert_eq!(cats[0].fields[1].field_type, CatalogFieldType::Number);
        assert_eq!(cats[1].name, "dermatology");
        assert_eq!(cats[1].description, None);
    }

    #[tokio::test]
    async fn list_catalogs_empty() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert!(cats.is_empty());
    }

    #[tokio::test]
    async fn list_catalogs_sets_user_agent() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .and(header(
                "user-agent",
                concat!("braze-sync/", env!("CARGO_PKG_VERSION")),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        client.list_catalogs().await.unwrap();
    }

    #[tokio::test]
    async fn list_catalogs_ignores_unknown_fields_in_response() {
        // Forward compat: a future Braze response with extra fields
        // (top-level and inside catalog entries) should still parse
        // because no struct in the chain uses deny_unknown_fields.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {
                        "name": "future",
                        "description": "tomorrow",
                        "future_metadata": {"foo": "bar"},
                        "num_items": 1234,
                        "fields": [
                            {"name": "id", "type": "string", "extra": "ignored"}
                        ]
                    }
                ],
                "future_top_level": {"whatever": true},
                "message": "success"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "future");
    }

    #[tokio::test]
    async fn list_catalogs_errors_when_next_cursor_present() {
        // Regression guard: v0.2.0 silently returned page 1 here.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {"name": "cardiology", "fields": [{"name": "id", "type": "string"}]}
                ],
                "next_cursor": "abc123"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        match err {
            BrazeApiError::PaginationNotImplemented { endpoint, detail } => {
                assert_eq!(endpoint, "/catalogs");
                assert!(detail.contains("next_cursor"), "detail: {detail}");
                assert!(detail.contains("1 catalog"), "detail: {detail}");
            }
            other => panic!("expected PaginationNotImplemented, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_catalogs_empty_string_cursor_is_treated_as_no_more_pages() {
        // Some paginated APIs return `next_cursor: ""` on the last
        // page instead of omitting the field. Treat that as "no more
        // pages" rather than tripping the fail-closed guard — the
        // alternative would turn every workspace under one page into
        // an error.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [{"name": "only", "fields": []}],
                "next_cursor": ""
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "only");
    }

    #[tokio::test]
    async fn unauthorized_returns_typed_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid api key"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn server_error_carries_status_and_body() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(500).set_body_string("internal explosion"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        match err {
            BrazeApiError::Http { status, body } => {
                assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
                assert!(body.contains("internal explosion"));
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn retries_on_429_and_succeeds() {
        let server = MockServer::start().await;
        // wiremock matches the *most recently mounted* mock first; the
        // limited 429 mock is mounted second so it preempts until used
        // up, after which the success mock takes over.
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [{"name": "after_retry", "fields": []}]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "after_retry");
    }

    #[tokio::test]
    async fn retries_exhausted_returns_rate_limit_exhausted() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        assert!(
            matches!(err, BrazeApiError::RateLimitExhausted),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn get_catalog_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/cardiology"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {"name": "cardiology", "fields": [{"name": "id", "type": "string"}]}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cat = client.get_catalog("cardiology").await.unwrap();
        assert_eq!(cat.name, "cardiology");
        assert_eq!(cat.fields.len(), 1);
    }

    #[tokio::test]
    async fn get_catalog_404_is_mapped_to_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/missing"))
            .respond_with(ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_catalog("missing").await.unwrap_err();
        match err {
            BrazeApiError::NotFound { resource } => assert!(resource.contains("missing")),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_catalog_empty_response_array_is_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/ghost"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_catalog("ghost").await.unwrap_err();
        assert!(matches!(err, BrazeApiError::NotFound { .. }), "got {err:?}");
    }

    #[tokio::test]
    async fn debug_does_not_leak_api_key() {
        let server = MockServer::start().await;
        let client = make_client(&server);
        let dbg = format!("{client:?}");
        assert!(!dbg.contains("test-key"), "leaked api key in: {dbg}");
        assert!(dbg.contains("<redacted>"));
    }

    #[tokio::test]
    async fn add_catalog_field_happy_path_sends_correct_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .and(header("authorization", "Bearer test-key"))
            .and(body_json(json!({
                "fields": [{"name": "severity_level", "type": "number"}]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "severity_level".into(),
            field_type: CatalogFieldType::Number,
        };
        client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn add_catalog_field_unauthorized_propagates() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid key"))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "x".into(),
            field_type: CatalogFieldType::String,
        };
        let err = client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn add_catalog_field_retries_on_429_then_succeeds() {
        let server = MockServer::start().await;
        // Success mounted first; the limited 429 mock is mounted second
        // and wiremock matches the most-recently-mounted one until it
        // exhausts its `up_to_n_times` budget.
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"message": "ok"})))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "x".into(),
            field_type: CatalogFieldType::String,
        };
        client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn create_catalog_happy_path_sends_correct_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .and(header("authorization", "Bearer test-key"))
            .and(body_json(json!({
                "catalogs": [{
                    "name": "cardiology",
                    "description": "Cardiology catalog",
                    "fields": [
                        {"name": "id", "type": "string"},
                        {"name": "severity_level", "type": "number"}
                    ]
                }]
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "cardiology".into(),
            description: Some("Cardiology catalog".into()),
            fields: vec![
                CatalogField {
                    name: "id".into(),
                    field_type: CatalogFieldType::String,
                },
                CatalogField {
                    name: "severity_level".into(),
                    field_type: CatalogFieldType::Number,
                },
            ],
        };
        client.create_catalog(&cat).await.unwrap();
    }

    #[tokio::test]
    async fn create_catalog_hoists_id_field_to_first_position() {
        // Braze returns HTTP 400 `id-not-first-column` when fields[0]
        // is not `id`. Repos exported by braze-sync sort fields
        // alphabetically on disk, so a literal `id` lands mid-array;
        // create_catalog must normalize before sending.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .and(body_json(json!({
                "catalogs": [{
                    "name": "alpha",
                    "fields": [
                        {"name": "id", "type": "string"},
                        {"name": "URL", "type": "string"},
                        {"name": "author", "type": "string"},
                        {"name": "title", "type": "string"}
                    ]
                }]
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "alpha".into(),
            description: None,
            fields: vec![
                CatalogField {
                    name: "URL".into(),
                    field_type: CatalogFieldType::String,
                },
                CatalogField {
                    name: "author".into(),
                    field_type: CatalogFieldType::String,
                },
                CatalogField {
                    name: "id".into(),
                    field_type: CatalogFieldType::String,
                },
                CatalogField {
                    name: "title".into(),
                    field_type: CatalogFieldType::String,
                },
            ],
        };
        client.create_catalog(&cat).await.unwrap();
    }

    #[tokio::test]
    async fn create_catalog_omits_description_when_none() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .and(body_json(json!({
                "catalogs": [{
                    "name": "minimal",
                    "fields": [{"name": "id", "type": "string"}]
                }]
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "minimal".into(),
            description: None,
            fields: vec![CatalogField {
                name: "id".into(),
                field_type: CatalogFieldType::String,
            }],
        };
        client.create_catalog(&cat).await.unwrap();
    }

    #[tokio::test]
    async fn create_catalog_duplicate_name_propagates_400() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(400).set_body_json(json!({
                "errors": [{
                    "id": "catalog-name-already-exists",
                    "message": "A catalog with that name already exists"
                }]
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "existing".into(),
            description: None,
            fields: vec![],
        };
        let err = client.create_catalog(&cat).await.unwrap_err();
        assert!(
            matches!(
                &err,
                BrazeApiError::Http { status, body }
                    if *status == StatusCode::BAD_REQUEST
                        && body.contains("catalog-name-already-exists")
            ),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn create_catalog_unauthorized_propagates() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid key"))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "x".into(),
            description: None,
            fields: vec![],
        };
        let err = client.create_catalog(&cat).await.unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn create_catalog_retries_on_429_then_succeeds() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({"message": "ok"})))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cat = Catalog {
            name: "x".into(),
            description: None,
            fields: vec![CatalogField {
                name: "id".into(),
                field_type: CatalogFieldType::String,
            }],
        };
        client.create_catalog(&cat).await.unwrap();
    }

    #[tokio::test]
    async fn delete_catalog_field_happy_path_uses_segment_encoded_path() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/catalogs/cardiology/fields/legacy_code"))
            .and(header("authorization", "Bearer test-key"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = make_client(&server);
        client
            .delete_catalog_field("cardiology", "legacy_code")
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn delete_catalog_field_server_error_returns_http() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/catalogs/cardiology/fields/x"))
            .respond_with(ResponseTemplate::new(500).set_body_string("oops"))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let err = client
            .delete_catalog_field("cardiology", "x")
            .await
            .unwrap_err();
        match err {
            BrazeApiError::Http { status, body } => {
                assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
                assert!(body.contains("oops"));
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }
}