zammad-api 0.4.0

Async, idiomatic Rust client for the Zammad Service Platform
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
//! Knowledge Base ("FAQ") endpoints.
//!
//! Zammad's Knowledge Base API does not hand back plain records the way the
//! ticket or user endpoints do. Instead it returns an *assets* bundle: a set of
//! id-keyed maps (`KnowledgeBaseAnswer`, `KnowledgeBaseAnswerTranslation`,
//! `KnowledgeBaseAnswerTranslationContent`, `KnowledgeBaseCategory`, ...) that
//! the caller is expected to stitch together. This module hides that stitching
//! and exposes flat [`KbAnswer`] / [`KbSearchHit`] values.
//!
//! The following operations are provided:
//!
//! - [`KnowledgeBaseApi::list`] — every answer with its title and category
//!   (no body).
//! - [`KnowledgeBaseApi::search`] — full-text search, returning highlighted
//!   title/body snippets.
//! - [`KnowledgeBaseApi::get`] — a single answer including its full body.
//! - [`KnowledgeBaseApi::create_answer`] /
//!   [`KnowledgeBaseApi::update_answer`] /
//!   [`KnowledgeBaseApi::delete_answer`] — answer writes, including the
//!   publishing state machine.
//! - [`KnowledgeBaseApi::list_knowledge_bases`] /
//!   [`KnowledgeBaseApi::list_categories`] /
//!   [`KnowledgeBaseApi::get_category`] — the structure, read from the
//!   `init` bundle.
//! - [`KnowledgeBaseApi::create_category`] /
//!   [`KnowledgeBaseApi::update_category`] /
//!   [`KnowledgeBaseApi::delete_category`] — category CRUD.
//!
//! The answer body is not part of the default `init` payload; it is fetched in
//! a second `init` call that names the wanted
//! `answer_translation_content_ids`.

use std::collections::BTreeMap;

use reqwest::Method;
use serde::Deserialize;

use crate::client::Client;
use crate::error::{Error, Result};

const INIT_PATH: &str = "api/v1/knowledge_bases/init";
const SEARCH_PATH: &str = "api/v1/knowledge_bases/search";

/// Icon used when [`NewKbCategory::icon`] is `None`; Zammad requires an
/// icon on category create.
const DEFAULT_CATEGORY_ICON: &str = "f115";

/// Knowledge Base (FAQ) endpoints.
#[derive(Debug)]
pub struct KnowledgeBaseApi<'a> {
    client: &'a Client,
}

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

    /// List every answer known to the instance, flattened to
    /// [`KbAnswer`]s (title + category, no body).
    ///
    /// `POST /api/v1/knowledge_bases/init`.
    pub async fn list(&self) -> Result<Vec<KbAnswer>> {
        let assets = self.init(&[]).await?;
        let mut answers: Vec<KbAnswer> = assets
            .answers
            .iter()
            .map(|(&id, raw)| assets.to_answer(id, raw, None))
            .collect();
        answers.sort_by_key(|a| a.id);
        Ok(answers)
    }

    /// Fetch a single answer by its numeric id, including its full body.
    ///
    /// Returns [`Error::NotFound`] when no answer with that id exists.
    ///
    /// Issues two `POST /api/v1/knowledge_bases/init` calls: one for the
    /// structure and one that requests the answer's translation content.
    pub async fn get(&self, answer_id: u64) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let raw = assets.answers.get(&answer_id).ok_or(Error::NotFound)?;

        // The body lives on the translation's content record, addressed by
        // `content_id`. Ask a second `init` to include it.
        let content_id = assets.primary_translation(raw).and_then(|t| t.content_id);
        let body = self.body_of(content_id).await?;

        Ok(assets.to_answer(answer_id, raw, Some(body)))
    }

    /// Every knowledge base on the instance (from the `init` bundle).
    ///
    /// `POST /api/v1/knowledge_bases/init`.
    pub async fn list_knowledge_bases(&self) -> Result<Vec<KbInfo>> {
        let assets = self.init(&[]).await?;
        let mut kbs: Vec<KbInfo> = assets
            .kbs
            .iter()
            .map(|(&id, raw)| assets.to_kb_info(id, raw))
            .collect();
        kbs.sort_by_key(|k| k.id);
        Ok(kbs)
    }

    /// Every category of every knowledge base (from the `init` bundle),
    /// sorted by id.
    ///
    /// `POST /api/v1/knowledge_bases/init`.
    pub async fn list_categories(&self) -> Result<Vec<KbCategory>> {
        let assets = self.init(&[]).await?;
        let mut categories: Vec<KbCategory> = assets
            .categories
            .iter()
            .filter(|(_, raw)| raw.knowledge_base_id.is_some())
            .map(|(&id, raw)| assets.to_category(id, raw))
            .collect();
        categories.sort_by_key(|c| c.id);
        Ok(categories)
    }

    /// Fetch a single category by its numeric id.
    ///
    /// Returns [`Error::NotFound`] when no category with that id exists.
    ///
    /// `POST /api/v1/knowledge_bases/init`.
    pub async fn get_category(&self, category_id: u64) -> Result<KbCategory> {
        let assets = self.init(&[]).await?;
        let raw = assets.categories.get(&category_id).ok_or(Error::NotFound)?;
        Ok(assets.to_category(category_id, raw))
    }

    /// Create a category in the given knowledge base (primary locale).
    ///
    /// `kb_id` is explicit because a new category cannot be resolved from
    /// `init`. Returns [`Error::NotFound`] when the kb_id is unknown and
    /// [`Error::Config`] when the KB has no locale.
    ///
    /// `POST /api/v1/knowledge_bases/:kb_id/categories`.
    pub async fn create_category(&self, kb_id: u64, category: NewKbCategory) -> Result<KbCategory> {
        let assets = self.init(&[]).await?;
        if !assets.kbs.contains_key(&kb_id) {
            return Err(Error::NotFound);
        }
        let kb_locale_id = assets
            .primary_locale_id(kb_id)
            .ok_or_else(|| Error::Config(format!("no locale found for knowledge base {kb_id}")))?;

        let icon = category.icon.unwrap_or_else(|| DEFAULT_CATEGORY_ICON.to_string());
        let payload = serde_json::json!({
            "category_icon": icon,
            "parent_id": category.parent_id,
            "translations_attributes": [{
                "kb_locale_id": kb_locale_id,
                "title": category.title,
            }],
        });

        let path = format!("api/v1/knowledge_bases/{kb_id}/categories");
        let req = self.client.request(Method::POST, &path).json(&payload);
        let created: CategoryWriteResponse = self.client.send_json(req).await?;
        self.get_category(created.id).await
    }

    /// Partial update; kb_id resolved from the category via `init`.
    ///
    /// An all-`None` patch skips the HTTP call and returns the current
    /// state. Returns [`Error::NotFound`] when no category with that id
    /// exists.
    ///
    /// `PATCH /api/v1/knowledge_bases/:kb_id/categories/:id`.
    pub async fn update_category(&self, category_id: u64, patch: KbCategoryPatch) -> Result<KbCategory> {
        let assets = self.init(&[]).await?;
        let raw = assets.categories.get(&category_id).ok_or(Error::NotFound)?;
        if patch.title.is_none() && patch.icon.is_none() && patch.parent_id.is_none() {
            return Ok(assets.to_category(category_id, raw));
        }
        let kb_id = raw
            .knowledge_base_id
            .ok_or_else(|| Error::Config(format!("no knowledge base found for category {category_id}")))?;

        let mut payload = serde_json::json!({});
        if let Some(icon) = &patch.icon {
            payload["category_icon"] = serde_json::json!(icon);
        }
        if let Some(parent) = patch.parent_id {
            payload["parent_id"] = serde_json::json!(parent);
        }
        if let Some(title) = &patch.title {
            let translation_id = *raw
                .translation_ids
                .first()
                .ok_or_else(|| Error::Config("category has no translation to update".into()))?;
            payload["translations_attributes"] = serde_json::json!([{
                "id": translation_id,
                "title": title,
            }]);
        }

        let path = format!("api/v1/knowledge_bases/{kb_id}/categories/{category_id}");
        let req = self.client.request(Method::PATCH, &path).json(&payload);
        let _: CategoryWriteResponse = self.client.send_json(req).await?;
        self.get_category(category_id).await
    }

    /// Delete a category.
    ///
    /// Zammad refuses (422) when the category still has answers or child
    /// categories; that surfaces as [`Error::Api`].
    ///
    /// `DELETE /api/v1/knowledge_bases/:kb_id/categories/:id`.
    pub async fn delete_category(&self, category_id: u64) -> Result<()> {
        let assets = self.init(&[]).await?;
        let raw = assets.categories.get(&category_id).ok_or(Error::NotFound)?;
        let kb_id = raw
            .knowledge_base_id
            .ok_or_else(|| Error::Config(format!("no knowledge base found for category {category_id}")))?;
        let path = format!("api/v1/knowledge_bases/{kb_id}/categories/{category_id}");
        let req = self.client.request(Method::DELETE, &path);
        self.client.send_unit(req).await
    }

    /// Create a new answer in a category, in the knowledge base's primary
    /// locale.
    ///
    /// When [`NewKbAnswer::published`] is `true` a second
    /// `POST .../answers/:id/publish` call makes it public right away;
    /// otherwise it is left as a draft. The knowledge base and locale are
    /// resolved from the category.
    ///
    /// `POST /api/v1/knowledge_bases/:kb_id/answers`.
    pub async fn create_answer(&self, answer: NewKbAnswer) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let kb_id = assets.kb_of_category(answer.category_id).ok_or_else(|| {
            Error::Config(format!(
                "no knowledge base found for category {}",
                answer.category_id
            ))
        })?;
        let kb_locale_id = assets
            .primary_locale_id(kb_id)
            .ok_or_else(|| Error::Config(format!("no locale found for knowledge base {kb_id}")))?;

        let payload = serde_json::json!({
            "category_id": answer.category_id,
            "translations_attributes": [{
                "title": answer.title,
                "kb_locale_id": kb_locale_id,
                "content_attributes": { "body": answer.body },
            }],
        });

        let path = format!("api/v1/knowledge_bases/{kb_id}/answers");
        let req = self.client.request(Method::POST, &path).json(&payload);
        let created: AnswerWriteResponse = self.client.send_json(req).await?;
        if answer.published {
            self.set_published(created.id, kb_id, true).await?;
        }
        self.get(created.id).await
    }

    /// Update an existing answer's title, body, and/or published state. Fields
    /// left as `None` in the [`KbAnswerPatch`] are preserved.
    ///
    /// Returns [`Error::NotFound`] when no answer with that id exists.
    ///
    /// `PATCH /api/v1/knowledge_bases/:kb_id/answers/:id`.
    pub async fn update_answer(&self, answer_id: u64, patch: KbAnswerPatch) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let raw = assets.answers.get(&answer_id).ok_or(Error::NotFound)?;
        let category_id = raw
            .category_id
            .ok_or_else(|| Error::Config("answer has no category".into()))?;
        let kb_id = assets.kb_of_category(category_id).ok_or_else(|| {
            Error::Config(format!(
                "no knowledge base found for category {category_id}"
            ))
        })?;
        let kb_locale_id = assets
            .primary_locale_id(kb_id)
            .ok_or_else(|| Error::Config(format!("no locale found for knowledge base {kb_id}")))?;

        let translation_id = *raw
            .translation_ids
            .first()
            .ok_or_else(|| Error::Config("answer has no translation to update".into()))?;
        let translation = assets
            .translations
            .get(&translation_id)
            .ok_or_else(|| Error::Config("answer translation missing from payload".into()))?;
        let content_id = translation.content_id;

        // Merge: keep the current title/body for whichever field the caller
        // left unset, so a partial update never blanks the other.
        let title = match patch.title {
            Some(t) => t,
            None => translation.title.clone().unwrap_or_default(),
        };
        let body = match patch.body {
            Some(b) => b,
            None => self.body_of(content_id).await?.unwrap_or_default(),
        };

        // `content_attributes` is addressed by the translation's `id`;
        // Zammad updates the existing content in place.
        let payload = serde_json::json!({
            "category_id": category_id,
            "translations_attributes": [{
                "id": translation_id,
                "kb_locale_id": kb_locale_id,
                "title": title,
                "content_attributes": { "body": body },
            }],
        });

        let path = format!("api/v1/knowledge_bases/{kb_id}/answers/{answer_id}");
        let req = self.client.request(Method::PATCH, &path).json(&payload);
        let _: AnswerWriteResponse = self.client.send_json(req).await?;
        if let Some(published) = patch.published {
            self.set_published(answer_id, kb_id, published).await?;
        }
        self.get(answer_id).await
    }

    /// Delete an answer.
    ///
    /// The knowledge base is resolved answer → category → kb.
    ///
    /// `DELETE /api/v1/knowledge_bases/:kb_id/answers/:id`.
    pub async fn delete_answer(&self, answer_id: u64) -> Result<()> {
        let assets = self.init(&[]).await?;
        let raw = assets.answers.get(&answer_id).ok_or(Error::NotFound)?;
        let category_id = raw
            .category_id
            .ok_or_else(|| Error::Config("answer has no category".into()))?;
        let kb_id = assets.kb_of_category(category_id).ok_or_else(|| {
            Error::Config(format!(
                "no knowledge base found for category {category_id}"
            ))
        })?;
        let path = format!("api/v1/knowledge_bases/{kb_id}/answers/{answer_id}");
        let req = self.client.request(Method::DELETE, &path);
        self.client.send_unit(req).await
    }

    /// Fetch the body for a translation content id, if any.
    async fn body_of(&self, content_id: Option<u64>) -> Result<Option<String>> {
        let Some(cid) = content_id else {
            return Ok(None);
        };
        let assets = self.init(&[cid]).await?;
        Ok(assets.contents.get(&cid).and_then(|c| c.body.clone()))
    }

    /// Move an answer in the publishing state machine: `publish` makes it
    /// public, `has_publishing_update` (with all state timestamps cleared)
    /// reverts it to a draft.
    async fn set_published(&self, answer_id: u64, kb_id: u64, published: bool) -> Result<()> {
        if published {
            let path = format!("api/v1/knowledge_bases/{kb_id}/answers/{answer_id}/publish");
            let req = self.client.request(Method::POST, &path);
            self.client.send_unit(req).await
        } else {
            let path = format!(
                "api/v1/knowledge_bases/{kb_id}/answers/{answer_id}/has_publishing_update"
            );
            let body = serde_json::json!({
                "published_at": null,
                "internal_at": null,
                "archived_at": null,
            });
            let req = self.client.request(Method::POST, &path).json(&body);
            self.client.send_unit(req).await
        }
    }

    /// Full-text search across the Knowledge Base.
    ///
    /// Returns a builder; call [`SearchKnowledgeBase::send`] to run it.
    pub fn search(&self, query: impl Into<String>) -> SearchKnowledgeBase<'a> {
        SearchKnowledgeBase {
            client: self.client,
            query: query.into(),
            flavor: "public".to_string(),
            per_page: 50,
        }
    }

    /// `POST /api/v1/knowledge_bases/init`, optionally requesting the body
    /// content for the given answer-translation content ids.
    async fn init(&self, content_ids: &[u64]) -> Result<KbAssets> {
        let body = serde_json::json!({ "answer_translation_content_ids": content_ids });
        let req = self.client.request(Method::POST, INIT_PATH).json(&body);
        self.client.send_json(req).await
    }
}

/// Builder for `POST /api/v1/knowledge_bases/search`.
#[derive(Debug)]
pub struct SearchKnowledgeBase<'a> {
    client: &'a Client,
    query: String,
    flavor: String,
    per_page: u32,
}

impl SearchKnowledgeBase<'_> {
    /// Result flavor. `"public"` (the default) searches published,
    /// publicly-visible answers; `"agent"` also covers answers only visible
    /// to signed-in agents.
    pub fn flavor(mut self, flavor: impl Into<String>) -> Self {
        self.flavor = flavor.into();
        self
    }

    /// Maximum number of hits to return (default 50).
    pub fn per_page(mut self, n: u32) -> Self {
        self.per_page = n;
        self
    }

    /// Run the search.
    pub async fn send(self) -> Result<Vec<KbSearchHit>> {
        let body = serde_json::json!({
            "query": self.query,
            "flavor": self.flavor,
            "per_page": self.per_page,
            "include_subtitle": true,
        });
        let req = self.client.request(Method::POST, SEARCH_PATH).json(&body);
        let resp: SearchResponse = self.client.send_json(req).await?;

        // `details` carries the presentable fields (title, body snippet,
        // category subtitle, url); `id` there is the answer *translation* id.
        // Resolve each to its stable answer id via `init` so callers can hand
        // the id straight to [`KnowledgeBaseApi::get`].
        let hits = resp.details;
        if hits.is_empty() {
            return Ok(Vec::new());
        }

        let assets = KnowledgeBaseApi::new(self.client).init(&[]).await?;
        Ok(hits
            .into_iter()
            .map(|d| KbSearchHit {
                answer_id: assets.translations.get(&d.id).map(|t| t.answer_id),
                translation_id: d.id,
                title: strip_highlight(d.title),
                category: d.subtitle,
                snippet: strip_highlight(d.body),
                url: d.url,
            })
            .collect())
    }
}

/// A single Knowledge Base answer, flattened from Zammad's assets bundle.
#[derive(Debug, Clone)]
pub struct KbAnswer {
    /// Numeric answer id (stable; accepted by [`KnowledgeBaseApi::get`]).
    pub id: u64,
    /// Answer title, in the Knowledge Base's primary locale.
    pub title: Option<String>,
    /// Id of the category the answer belongs to.
    pub category_id: Option<u64>,
    /// Title of that category, in the primary locale.
    pub category: Option<String>,
    /// Whether the answer has been published.
    pub published: bool,
    /// The answer body (HTML). Only populated by [`KnowledgeBaseApi::get`];
    /// always `None` for [`KnowledgeBaseApi::list`].
    pub body: Option<String>,
}

/// Fields for creating a Knowledge Base answer via
/// [`KnowledgeBaseApi::create_answer`].
#[derive(Debug, Clone)]
pub struct NewKbAnswer {
    /// Category the answer belongs to. The knowledge base and locale are
    /// resolved from it.
    pub category_id: u64,
    /// Answer title.
    pub title: String,
    /// Answer body (HTML or plain text).
    pub body: String,
    /// Publish the answer immediately (`true`) or leave it a draft (`false`).
    pub published: bool,
}

/// A partial update for [`KnowledgeBaseApi::update_answer`]. Every field is
/// optional; `None` leaves the current value untouched.
#[derive(Debug, Clone, Default)]
pub struct KbAnswerPatch {
    /// New title.
    pub title: Option<String>,
    /// New body (HTML or plain text).
    pub body: Option<String>,
    /// `Some(true)` publishes, `Some(false)` reverts to a draft, `None` leaves
    /// the published state unchanged.
    pub published: Option<bool>,
}

/// A single full-text search hit.
#[derive(Debug, Clone)]
pub struct KbSearchHit {
    /// Stable answer id, resolved from the matched translation. `None` only if
    /// the translation could not be found in the structure payload.
    pub answer_id: Option<u64>,
    /// Id of the answer *translation* that matched.
    pub translation_id: u64,
    /// Answer title (search highlight markers stripped).
    pub title: Option<String>,
    /// Category the answer sits under.
    pub category: Option<String>,
    /// A snippet of the body around the match (highlight markers stripped).
    pub snippet: Option<String>,
    /// Relative help-center URL of the answer.
    pub url: Option<String>,
}

/// A knowledge base, as listed by
/// [`KnowledgeBaseApi::list_knowledge_bases`].
#[derive(Debug, Clone)]
pub struct KbInfo {
    /// Numeric knowledge base id.
    pub id: u64,
    /// Title in the KB's primary locale (from `KnowledgeBaseTranslation`),
    /// else first.
    pub title: Option<String>,
    /// Whether the knowledge base is active.
    pub active: bool,
}

/// A Knowledge Base category, flattened from Zammad's assets bundle.
#[derive(Debug, Clone)]
pub struct KbCategory {
    /// Numeric category id (stable; accepted by the category methods).
    pub id: u64,
    /// Id of the knowledge base the category belongs to.
    pub knowledge_base_id: u64,
    /// Id of the parent category, or `None` for a top-level category.
    pub parent_id: Option<u64>,
    /// FontAwesome icon code (e.g. `"f115"`).
    pub icon: Option<String>,
    /// Sort position within its parent.
    pub position: Option<u64>,
    /// Title in the KB's primary locale (first listed translation).
    pub title: Option<String>,
    /// Ids of the answers in this category.
    pub answer_ids: Vec<u64>,
    /// Ids of the direct child categories.
    pub child_ids: Vec<u64>,
    /// Creation timestamp (ISO 8601).
    pub created_at: Option<String>,
    /// Last-update timestamp (ISO 8601).
    pub updated_at: Option<String>,
}

/// Fields for creating a Knowledge Base category via
/// [`KnowledgeBaseApi::create_category`].
///
/// `icon: None` → `"f115"` (the docs' example icon; Zammad requires an
/// icon). `parent_id: None` → top-level category.
#[derive(Debug, Clone)]
pub struct NewKbCategory {
    /// Category title (primary locale).
    pub title: String,
    /// FontAwesome icon code; `None` falls back to `"f115"`.
    pub icon: Option<String>,
    /// Parent category id; `None` creates a top-level category.
    pub parent_id: Option<u64>,
}

/// A partial update for [`KnowledgeBaseApi::update_category`]. Every field is
/// optional; `None` leaves the current value untouched.
#[derive(Debug, Clone, Default)]
pub struct KbCategoryPatch {
    /// New title.
    pub title: Option<String>,
    /// New FontAwesome icon code.
    pub icon: Option<String>,
    /// Tri-state `parent_id`: `None` = unchanged, `Some(None)` = clear
    /// parent, `Some(Some(id))` = set parent.
    pub parent_id: Option<Option<u64>>,
}

// --- wire types -------------------------------------------------------------

/// The `init` assets bundle, with only the maps this module joins on.
#[derive(Debug, Default, Deserialize)]
struct KbAssets {
    #[serde(rename = "KnowledgeBaseAnswer", default)]
    answers: BTreeMap<u64, RawAnswer>,
    #[serde(rename = "KnowledgeBaseAnswerTranslation", default)]
    translations: BTreeMap<u64, RawTranslation>,
    #[serde(rename = "KnowledgeBaseAnswerTranslationContent", default)]
    contents: BTreeMap<u64, RawContent>,
    #[serde(rename = "KnowledgeBaseCategory", default)]
    categories: BTreeMap<u64, RawCategory>,
    #[serde(rename = "KnowledgeBaseCategoryTranslation", default)]
    category_translations: BTreeMap<u64, RawCategoryTranslation>,
    #[serde(rename = "KnowledgeBaseLocale", default)]
    locales: BTreeMap<u64, RawLocale>,
    #[serde(rename = "KnowledgeBase", default)]
    kbs: BTreeMap<u64, RawKb>,
    #[serde(rename = "KnowledgeBaseTranslation", default)]
    kb_translations: BTreeMap<u64, RawKbTranslation>,
}

impl KbAssets {
    /// The primary-locale translation for an answer (the first listed).
    fn primary_translation(&self, raw: &RawAnswer) -> Option<&RawTranslation> {
        raw.translation_ids
            .first()
            .and_then(|tid| self.translations.get(tid))
    }

    /// The knowledge base a category belongs to.
    fn kb_of_category(&self, category_id: u64) -> Option<u64> {
        self.categories
            .get(&category_id)
            .and_then(|c| c.knowledge_base_id)
    }

    /// The primary `kb_locale_id` of a knowledge base (needed to address a
    /// translation on write). Falls back to that KB's first locale.
    fn primary_locale_id(&self, kb_id: u64) -> Option<u64> {
        let mut first = None;
        for (&id, loc) in &self.locales {
            if loc.knowledge_base_id != kb_id {
                continue;
            }
            if loc.primary {
                return Some(id);
            }
            first.get_or_insert(id);
        }
        first
    }

    /// Build a [`KbAnswer`]. `body` is `Some(...)` for a fetched answer (the
    /// inner `Option` being whether a body actually exists), `None` for a
    /// listing where the body was never requested.
    fn to_answer(&self, id: u64, raw: &RawAnswer, body: Option<Option<String>>) -> KbAnswer {
        let title = self.primary_translation(raw).and_then(|t| t.title.clone());
        let category = raw
            .category_id
            .and_then(|cid| self.categories.get(&cid))
            .and_then(|c| c.translation_ids.first())
            .and_then(|ctid| self.category_translations.get(ctid))
            .and_then(|ct| ct.title.clone());
        KbAnswer {
            id,
            title,
            category_id: raw.category_id,
            category,
            published: raw.published_at.is_some(),
            body: body.flatten(),
        }
    }

    /// Build a [`KbCategory`]. The title is the primary-locale translation
    /// when the KB's primary locale is known, else the first listed one.
    fn to_category(&self, id: u64, raw: &RawCategory) -> KbCategory {
        KbCategory {
            id,
            knowledge_base_id: raw.knowledge_base_id.unwrap_or_default(),
            parent_id: raw.parent_id,
            icon: raw.category_icon.clone(),
            position: raw.position,
            title: self.category_title(raw),
            answer_ids: raw.answer_ids.clone(),
            child_ids: raw.child_ids.clone(),
            created_at: raw.created_at.clone(),
            updated_at: raw.updated_at.clone(),
        }
    }

    /// The category title: the translation in the KB's primary locale when
    /// both locale ids are known, else the first listed translation.
    fn category_title(&self, raw: &RawCategory) -> Option<String> {
        let primary = raw
            .knowledge_base_id
            .and_then(|kb| self.primary_locale_id(kb));
        for tid in &raw.translation_ids {
            let Some(ct) = self.category_translations.get(tid) else {
                continue;
            };
            if let (Some(ct_locale), Some(primary)) = (ct.kb_locale_id, primary) {
                if ct_locale == primary {
                    return ct.title.clone();
                }
            }
        }
        raw.translation_ids
            .first()
            .and_then(|tid| self.category_translations.get(tid))
            .and_then(|ct| ct.title.clone())
    }

    /// Build a [`KbInfo`]. The title is the `kb_translations` entry whose
    /// locale is the KB's primary one, else the first entry belonging to
    /// that KB (via its locale).
    fn to_kb_info(&self, id: u64, raw: &RawKb) -> KbInfo {
        let primary = self.primary_locale_id(id);
        let title = self
            .kb_translations
            .values()
            .find(|t| matches!((t.kb_locale_id, primary), (Some(l), Some(p)) if l == p))
            .or_else(|| {
                self.kb_translations.values().find(|t| {
                    t.kb_locale_id
                        .and_then(|l| self.locales.get(&l))
                        .is_some_and(|loc| loc.knowledge_base_id == id)
                })
            })
            .and_then(|t| t.title.clone());
        KbInfo {
            id,
            title,
            active: raw.active,
        }
    }
}

#[derive(Debug, Deserialize)]
struct RawAnswer {
    #[serde(default)]
    category_id: Option<u64>,
    #[serde(default)]
    translation_ids: Vec<u64>,
    #[serde(default)]
    published_at: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawTranslation {
    answer_id: u64,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    content_id: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct RawContent {
    #[serde(default)]
    body: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawCategory {
    #[serde(default)]
    knowledge_base_id: Option<u64>,
    #[serde(default)]
    translation_ids: Vec<u64>,
    #[serde(default)]
    parent_id: Option<u64>,
    #[serde(default)]
    category_icon: Option<String>,
    #[serde(default)]
    position: Option<u64>,
    #[serde(default)]
    answer_ids: Vec<u64>,
    #[serde(default)]
    child_ids: Vec<u64>,
    #[serde(default)]
    created_at: Option<String>,
    #[serde(default)]
    updated_at: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawKb {
    #[serde(default)]
    active: bool,
}

#[derive(Debug, Deserialize)]
struct RawKbTranslation {
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    kb_locale_id: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct RawLocale {
    knowledge_base_id: u64,
    #[serde(default)]
    primary: bool,
}

#[derive(Debug, Deserialize)]
struct RawCategoryTranslation {
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    kb_locale_id: Option<u64>,
}

/// The `{ id }` envelope returned by category create/update.
#[derive(Debug, Deserialize)]
struct CategoryWriteResponse {
    id: u64,
}

/// The `{ id, assets }` envelope returned by answer create/update.
#[derive(Debug, Deserialize)]
struct AnswerWriteResponse {
    id: u64,
}

#[derive(Debug, Deserialize)]
struct SearchResponse {
    #[serde(default)]
    details: Vec<SearchDetail>,
}

#[derive(Debug, Deserialize)]
struct SearchDetail {
    id: u64,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    body: Option<String>,
    #[serde(default)]
    subtitle: Option<String>,
    #[serde(default)]
    url: Option<String>,
}

/// Drop the `<em>…</em>` markers Zammad wraps around matched terms in search
/// highlights, leaving plain text.
fn strip_highlight(s: Option<String>) -> Option<String> {
    s.map(|s| s.replace("<em>", "").replace("</em>", ""))
}