skybase 0.1.11

The Open-Source Backend & Developer Platform for the AT Protocol (Firebase for ATProto, powered by skyauth)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Strongly-typed ATProto Lexicon record models.
//!
//! Provides lightweight Serde representations of the ATProto records used across
//! Skybase-family applications: `com.atproto.repo.strongRef`, `app.bsky.feed.post`
//! (with reply refs, facets, and embeds), `app.bsky.graph.follow`,
//! `app.bsky.graph.list`, `app.bsky.graph.listitem`, and `app.bsky.graph.listblock`,
//! plus the `com.atproto.repo.listRecords` response envelope.

use serde::{Deserialize, Serialize};

use crate::lexicon::Facet;

/// Strong reference to an ATProto repository record (`com.atproto.repo.strongRef`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StrongRef {
    /// Canonical AT-URI (`at://{did}/{collection}/{rkey}`).
    pub uri: String,
    /// Content identifier (CID) hash string.
    pub cid: String,
}

impl StrongRef {
    /// Creates a new [`StrongRef`].
    #[must_use]
    pub fn new(uri: impl Into<String>, cid: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            cid: cid.into(),
        }
    }

    /// Extracts the authority DID from the record's AT-URI without allocating.
    #[must_use]
    pub fn did(&self) -> Option<&str> {
        let stripped = self.uri.strip_prefix("at://")?;
        let did = stripped.split('/').next()?;
        if did.starts_with("did:") {
            Some(did)
        } else {
            None
        }
    }
}

/// Reply references connecting a post to its thread root and immediate parent (`app.bsky.feed.post#replyRef`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ReplyRef {
    /// Reference to the thread root post.
    pub root: StrongRef,
    /// Reference to the immediate parent post being replied to.
    pub parent: StrongRef,
}

impl ReplyRef {
    /// Creates a new [`ReplyRef`].
    #[must_use]
    pub fn new(root: StrongRef, parent: StrongRef) -> Self {
        Self { root, parent }
    }

    /// Extracts the author DID of the immediate parent post.
    #[must_use]
    pub fn parent_did(&self) -> Option<&str> {
        self.parent.did()
    }

    /// Extracts the author DID of the thread root post.
    #[must_use]
    pub fn root_did(&self) -> Option<&str> {
        self.root.did()
    }
}

/// Quoted record embed reference (`app.bsky.embed.record`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordEmbed {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default)]
    pub record_type: Option<String>,
    /// Quoted record reference.
    pub record: StrongRef,
}

impl RecordEmbed {
    /// Creates a new [`RecordEmbed`].
    #[must_use]
    pub fn new(record: StrongRef) -> Self {
        Self {
            record_type: Some("app.bsky.embed.record".to_string()),
            record,
        }
    }
}

/// Quoted record combined with media attachments (`app.bsky.embed.recordWithMedia`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordWithMediaEmbed {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default)]
    pub record_type: Option<String>,
    /// Quoted record embed container.
    pub record: RecordEmbed,
    /// Media attachments (images, video, external).
    #[serde(default)]
    pub media: Option<serde_json::Value>,
}

impl RecordWithMediaEmbed {
    /// Creates a new [`RecordWithMediaEmbed`].
    #[must_use]
    pub fn new(record: RecordEmbed, media: Option<serde_json::Value>) -> Self {
        Self {
            record_type: Some("app.bsky.embed.recordWithMedia".to_string()),
            record,
            media,
        }
    }
}

/// Embedded content union on a post record (`app.bsky.feed.post#embed`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "$type")]
pub enum Embed {
    /// Quoted record embed (`app.bsky.embed.record`).
    #[serde(rename = "app.bsky.embed.record")]
    Record(RecordEmbed),
    /// Quoted record embed combined with media (`app.bsky.embed.recordWithMedia`).
    #[serde(rename = "app.bsky.embed.recordWithMedia")]
    RecordWithMedia(Box<RecordWithMediaEmbed>),
    /// Image attachments (`app.bsky.embed.images`).
    #[serde(rename = "app.bsky.embed.images")]
    Images(serde_json::Value),
    /// Image/media gallery embed (`app.bsky.embed.gallery`).
    #[serde(rename = "app.bsky.embed.gallery")]
    Gallery(serde_json::Value),
    /// External card embed (`app.bsky.embed.external`).
    #[serde(rename = "app.bsky.embed.external")]
    External(serde_json::Value),
    /// Video embed (`app.bsky.embed.video`).
    #[serde(rename = "app.bsky.embed.video")]
    Video(serde_json::Value),
    /// Unrecognized or future embed type.
    #[serde(other)]
    Unknown,
}

impl Embed {
    /// Returns the quoted record AT-URI if this embed is a quote (`Record` or `RecordWithMedia`).
    #[must_use]
    pub fn quote_uri(&self) -> Option<&str> {
        match self {
            Self::Record(r) => Some(r.record.uri.as_str()),
            Self::RecordWithMedia(rwm) => Some(rwm.record.record.uri.as_str()),
            _ => None,
        }
    }

    /// Returns the quoted record CID if this embed is a quote (`Record` or `RecordWithMedia`).
    #[must_use]
    pub fn quote_cid(&self) -> Option<&str> {
        match self {
            Self::Record(r) => Some(r.record.cid.as_str()),
            Self::RecordWithMedia(rwm) => Some(rwm.record.record.cid.as_str()),
            _ => None,
        }
    }

    /// Returns `true` if this embed contains a quoted record.
    #[must_use]
    pub fn is_quote(&self) -> bool {
        matches!(self, Self::Record(_) | Self::RecordWithMedia(_))
    }

    /// Extracts all attached image CIDs and optional alt texts from this embed.
    ///
    /// Supports direct image embeds (`app.bsky.embed.images`), gallery embeds
    /// (`app.bsky.embed.gallery`), and composite quote-with-media embeds (`app.bsky.embed.recordWithMedia`).
    #[must_use]
    pub fn extract_images(&self) -> Vec<(String, String)> {
        match self {
            Self::Images(val) => Self::extract_images_from_value(val),
            Self::Gallery(val) => Self::extract_gallery_items(val),
            Self::RecordWithMedia(rwm) => {
                if let Some(ref media) = rwm.media {
                    let mut imgs = Self::extract_images_from_value(media);
                    if imgs.is_empty() {
                        imgs = Self::extract_gallery_items(media);
                    }
                    imgs
                } else {
                    Vec::new()
                }
            }
            _ => Vec::new(),
        }
    }

    /// Extracts `(cid, alt)` pairs from an `app.bsky.embed.gallery` (or `images`) JSON object.
    #[must_use]
    pub fn extract_gallery_items(val: &serde_json::Value) -> Vec<(String, String)> {
        let Some(items) = val
            .get("items")
            .or_else(|| val.get("images"))
            .and_then(|v| v.as_array())
        else {
            return Vec::new();
        };

        let mut results = Vec::with_capacity(items.len());
        for item in items {
            let alt = item
                .get("alt")
                .or_else(|| item.get("media").and_then(|m| m.get("alt")))
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();

            let img_obj = item
                .get("image")
                .or_else(|| item.get("media").and_then(|m| m.get("image")));

            let cid = img_obj
                .and_then(|img| {
                    img.get("ref")
                        .and_then(|r| r.get("$link"))
                        .and_then(|l| l.as_str())
                        .or_else(|| img.get("cid").and_then(|c| c.as_str()))
                })
                .or_else(|| item.get("cid").and_then(|c| c.as_str()));

            if let Some(c) = cid.filter(|s| !s.is_empty()) {
                results.push((c.to_string(), alt));
            }
        }
        results
    }

    /// Internal helper extracting `(cid, alt)` pairs from an arbitrary JSON value.
    fn extract_images_from_value(val: &serde_json::Value) -> Vec<(String, String)> {
        let mut results = Vec::new();
        let images_array = if let Some(arr) = val.get("images").and_then(|v| v.as_array()) {
            arr
        } else if let Some(arr) = val.as_array() {
            arr
        } else {
            return results;
        };

        for item in images_array {
            let alt = item
                .get("alt")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();

            let cid = item
                .get("image")
                .and_then(|img| {
                    img.get("ref")
                        .and_then(|r| r.get("$link"))
                        .and_then(|l| l.as_str())
                        .or_else(|| img.get("cid").and_then(|c| c.as_str()))
                })
                .or_else(|| item.get("cid").and_then(|c| c.as_str()));

            if let Some(c) = cid {
                if !c.is_empty() {
                    results.push((c.to_string(), alt));
                }
            }
        }

        results
    }
}

/// Self-label values that classify a post as adult / NSFW content.
///
/// Mirrors the content-warning vocabulary used by `ATProto` clients for
/// `com.atproto.label.defs#selfLabels` (e.g. `porn`, `sexual`, `nudity`).
pub const NSFW_SELF_LABEL_VALUES: [&str; 10] = [
    "porn",
    "sexual",
    "nudity",
    "graphic-media",
    "graphic",
    "adult",
    "nsfw",
    "suggestive",
    "gore",
    "corpse",
];

/// Returns `true` if a post record carries an adult / NSFW author self-label.
///
/// Reads the `labels` object (`com.atproto.label.defs#selfLabels`) and inspects
/// its `values` array. Entries may be either `{ "val": "..." }` objects or bare
/// strings; comparison is case-insensitive.
#[must_use]
pub fn has_nsfw_self_label(record: &serde_json::Value) -> bool {
    let Some(values) = record
        .get("labels")
        .and_then(|labels| labels.get("values"))
        .and_then(serde_json::Value::as_array)
    else {
        return false;
    };

    values.iter().any(|entry| {
        let raw = entry
            .get("val")
            .and_then(serde_json::Value::as_str)
            .or_else(|| entry.as_str());
        raw.is_some_and(|val| {
            let trimmed = val.trim();
            NSFW_SELF_LABEL_VALUES
                .iter()
                .any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
                || SelfLabels::NSFW_LABELS
                    .iter()
                    .any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
        })
    })
}

/// Single self-applied label value (`com.atproto.label.defs#selfLabel`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SelfLabel {
    /// The short string name of the value or type of this label (e.g., `"porn"`, `"sexual"`, `"nudity"`, `"graphic-media"`).
    pub val: String,
}

impl SelfLabel {
    /// Creates a new [`SelfLabel`].
    #[must_use]
    pub fn new(val: impl Into<String>) -> Self {
        Self { val: val.into() }
    }
}

/// Metadata tag container on a record published by the author (`com.atproto.label.defs#selfLabels`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelfLabels {
    /// Optional lexicon type discriminator (`com.atproto.label.defs#selfLabels`).
    #[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
    pub record_type: Option<String>,
    /// Array of self-applied label values.
    #[serde(default)]
    pub values: Vec<SelfLabel>,
}

impl SelfLabels {
    /// Standard ATProto adult/NSFW content self-label identifiers.
    pub const NSFW_LABELS: &'static [&'static str] = &[
        "porn",
        "sexual",
        "nudity",
        "nsfw",
        "graphic-media",
        "graphic",
        "suggestive",
        "gore",
        "corpse",
        "adult",
    ];

    /// Returns `true` if any self-label matches a standard NSFW / adult-content label (case-insensitively).
    #[must_use]
    pub fn has_nsfw(&self) -> bool {
        self.values.iter().any(|l| {
            let trimmed = l.val.trim();
            Self::NSFW_LABELS
                .iter()
                .any(|nsfw| trimmed.eq_ignore_ascii_case(nsfw))
        })
    }

    /// Returns `true` if any self-label matches `target` case-insensitively.
    #[must_use]
    pub fn contains(&self, target: &str) -> bool {
        self.values
            .iter()
            .any(|l| l.val.trim().eq_ignore_ascii_case(target))
    }
}

/// ATProto post record model (`app.bsky.feed.post`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostRecord {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default)]
    pub record_type: Option<String>,
    /// Text body of the post.
    #[serde(default)]
    pub text: String,
    /// Optional reply references.
    #[serde(default)]
    pub reply: Option<ReplyRef>,
    /// Optional rich text facet annotations.
    #[serde(default)]
    pub facets: Option<Vec<Facet>>,
    /// Optional embedded media or quote post.
    #[serde(default)]
    pub embed: Option<Embed>,
    /// ISO-8601 creation timestamp.
    #[serde(default)]
    pub created_at: String,
    /// Optional language tags.
    #[serde(default)]
    pub langs: Option<Vec<String>>,
    /// Optional post hashtags or category tags.
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    /// Optional self-applied content labels (`com.atproto.label.defs#selfLabels`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<SelfLabels>,
}

impl PostRecord {
    /// Creates a minimal [`PostRecord`] with text and creation timestamp.
    #[must_use]
    pub fn new(text: impl Into<String>, created_at: impl Into<String>) -> Self {
        Self {
            record_type: Some("app.bsky.feed.post".to_string()),
            text: text.into(),
            reply: None,
            facets: None,
            embed: None,
            created_at: created_at.into(),
            langs: None,
            tags: None,
            labels: None,
        }
    }

    /// Sets the reply reference.
    #[must_use]
    pub fn with_reply(mut self, reply: ReplyRef) -> Self {
        self.reply = Some(reply);
        self
    }

    /// Sets rich text facets.
    #[must_use]
    pub fn with_facets(mut self, facets: Vec<Facet>) -> Self {
        self.facets = Some(facets);
        self
    }

    /// Sets an embedded item.
    #[must_use]
    pub fn with_embed(mut self, embed: Embed) -> Self {
        self.embed = Some(embed);
        self
    }

    /// Returns an iterator over all distinct DIDs mentioned in this post's facets.
    pub fn mentioned_dids(&self) -> impl Iterator<Item = &str> {
        self.facets
            .as_deref()
            .into_iter()
            .flatten()
            .flat_map(Facet::mentioned_dids)
    }

    /// Returns the quoted post AT-URI if present.
    #[must_use]
    pub fn quote_uri(&self) -> Option<&str> {
        self.embed.as_ref().and_then(Embed::quote_uri)
    }
}

/// ATProto graph follow record model (`app.bsky.graph.follow`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FollowRecord {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default)]
    pub record_type: Option<String>,
    /// Decentralized identifier (DID) of the account being followed.
    pub subject: String,
    /// ISO-8601 creation timestamp.
    pub created_at: String,
}

impl FollowRecord {
    /// Creates a new [`FollowRecord`].
    #[must_use]
    pub fn new(subject: impl Into<String>, created_at: impl Into<String>) -> Self {
        Self {
            record_type: Some("app.bsky.graph.follow".to_string()),
            subject: subject.into(),
            created_at: created_at.into(),
        }
    }
}

/// ATProto moderation list record model (`app.bsky.graph.list`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModListRecord {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
    pub record_type: Option<String>,
    /// List purpose identifier (`app.bsky.graph.defs#modlist`).
    pub purpose: String,
    /// Human-readable list title.
    pub name: String,
    /// Optional human-readable list description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Optional rich text facets for description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description_facets: Option<Vec<Facet>>,
    /// Optional avatar blob reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub avatar: Option<serde_json::Value>,
    /// Optional self-applied content labels (`com.atproto.label.defs#selfLabels`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<SelfLabels>,
    /// ISO-8601 creation timestamp.
    pub created_at: String,
}

impl ModListRecord {
    /// Creates a new moderation list record with default purpose `app.bsky.graph.defs#modlist`.
    #[must_use]
    pub fn new_modlist(
        name: impl Into<String>,
        description: Option<String>,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            record_type: Some("app.bsky.graph.list".to_string()),
            purpose: "app.bsky.graph.defs#modlist".to_string(),
            name: name.into(),
            description,
            description_facets: None,
            avatar: None,
            labels: None,
            created_at: created_at.into(),
        }
    }

    /// Creates a new generic list record with specified purpose.
    #[must_use]
    pub fn new(
        purpose: impl Into<String>,
        name: impl Into<String>,
        description: Option<String>,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            record_type: Some("app.bsky.graph.list".to_string()),
            purpose: purpose.into(),
            name: name.into(),
            description,
            description_facets: None,
            avatar: None,
            labels: None,
            created_at: created_at.into(),
        }
    }

    /// Checks whether this list record has the moderation list purpose.
    #[must_use]
    pub fn is_modlist(&self) -> bool {
        self.purpose == "app.bsky.graph.defs#modlist"
    }
}

/// ATProto list item record model (`app.bsky.graph.listitem`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListItemRecord {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
    pub record_type: Option<String>,
    /// Decentralized identifier (DID) of the account added to the list.
    pub subject: String,
    /// Canonical AT-URI of the parent moderation list (`at://{did}/app.bsky.graph.list/{rkey}`).
    pub list: String,
    /// ISO-8601 creation timestamp.
    pub created_at: String,
}

impl ListItemRecord {
    /// Creates a new [`ListItemRecord`].
    #[must_use]
    pub fn new(
        subject: impl Into<String>,
        list: impl Into<String>,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            record_type: Some("app.bsky.graph.listitem".to_string()),
            subject: subject.into(),
            list: list.into(),
            created_at: created_at.into(),
        }
    }
}

/// ATProto list block record model (`app.bsky.graph.listblock`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListBlockRecord {
    /// Optional lexicon type discriminator.
    #[serde(rename = "$type", default, skip_serializing_if = "Option::is_none")]
    pub record_type: Option<String>,
    /// Canonical AT-URI of the moderation list being blocked (`at://{did}/app.bsky.graph.list/{rkey}`).
    pub subject: String,
    /// ISO-8601 creation timestamp.
    pub created_at: String,
}

impl ListBlockRecord {
    /// Creates a new [`ListBlockRecord`] targeting a moderation list AT-URI.
    #[must_use]
    pub fn new(subject: impl Into<String>, created_at: impl Into<String>) -> Self {
        Self {
            record_type: Some("app.bsky.graph.listblock".to_string()),
            subject: subject.into(),
            created_at: created_at.into(),
        }
    }
}

/// A record item returned by `com.atproto.repo.listRecords`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RepoRecordItem<T = serde_json::Value> {
    /// Canonical AT-URI of the committed record.
    pub uri: String,
    /// Content identifier (CID) hash string.
    pub cid: String,
    /// The deserialized record value payload.
    pub value: T,
}

/// The response payload from `com.atproto.repo.listRecords`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ListRecordsResponse<T = serde_json::Value> {
    /// Array of committed records in the target collection.
    pub records: Vec<RepoRecordItem<T>>,
    /// Optional pagination cursor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
}

/// Formats a [`std::time::SystemTime`] as an ISO-8601 (RFC 3339) UTC timestamp string.
#[must_use]
pub fn format_system_time_iso8601(time: std::time::SystemTime) -> String {
    let dur = time
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or(std::time::Duration::ZERO);
    let total_secs = dur.as_secs();
    let millis = dur.subsec_millis();

    let days = (total_secs / 86400) as i64;
    let day_secs = (total_secs % 86400) as u32;

    let hour = day_secs / 3600;
    let minute = (day_secs % 3600) / 60;
    let second = day_secs % 60;

    // Euclidean affine civil calendar algorithm (Howard Hinnant)
    let z = days + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = (z - era * 146097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = (yoe as i64) + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };

    format!("{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
}

/// Convenience function returning the current UTC time as an ISO-8601 string.
#[must_use]
pub fn now_iso8601() -> String {
    format_system_time_iso8601(std::time::SystemTime::now())
}

/// Formats a Unix timestamp in whole seconds into an ISO-8601 / RFC 3339 UTC timestamp string (`YYYY-MM-DDTHH:MM:SSZ`).
#[must_use]
pub fn format_unix_secs_iso8601(secs: u64) -> String {
    let mut days = secs / 86400;
    let day_secs = secs % 86400;
    let hours = day_secs / 3600;
    let mins = (day_secs % 3600) / 60;
    let seconds = day_secs % 60;

    days += 719_468;
    let era = days / 146_097;
    let doe = days - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hours:02}:{mins:02}:{seconds:02}Z")
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;
    use std::time::{Duration, UNIX_EPOCH};

    #[test]
    fn test_format_system_time_epoch() {
        assert_eq!(
            format_system_time_iso8601(UNIX_EPOCH),
            "1970-01-01T00:00:00.000Z"
        );
    }

    #[test]
    fn test_format_system_time_known_date() {
        let time = UNIX_EPOCH + Duration::from_millis(1_790_906_400_500);
        assert_eq!(format_system_time_iso8601(time), "2026-10-02T02:00:00.500Z");
    }

    #[test]
    fn test_now_iso8601_non_empty() {
        let now = now_iso8601();
        assert!(now.ends_with('Z'));
        assert!(now.contains('T'));
    }

    #[test]
    fn test_strong_ref_did_extraction() {
        let r = StrongRef::new("at://did:plc:alice/app.bsky.feed.post/1", "bafy");
        assert_eq!(r.did(), Some("did:plc:alice"));
        let bad = StrongRef::new("at://alice.bsky.social/app.bsky.feed.post/1", "bafy");
        assert_eq!(bad.did(), None);
    }

    #[test]
    fn test_mod_list_record_serde_roundtrip() {
        let record = ModListRecord::new_modlist(
            "Test Mod List",
            Some("Description".to_string()),
            "2026-10-02T00:00:00.000Z",
        );
        let json = serde_json::to_string(&record).unwrap();
        assert!(json.contains("\"purpose\":\"app.bsky.graph.defs#modlist\""));
        let deserialized: ModListRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(record, deserialized);
        assert!(deserialized.is_modlist());
    }

    #[test]
    fn test_list_item_record_serde_roundtrip() {
        let record = ListItemRecord::new(
            "did:plc:badactor",
            "at://did:plc:alice/app.bsky.graph.list/123",
            "2026-10-02T00:00:00.000Z",
        );
        let json = serde_json::to_string(&record).unwrap();
        assert!(json.contains("\"subject\":\"did:plc:badactor\""));
        let deserialized: ListItemRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(record, deserialized);
    }

    #[test]
    fn test_embed_extract_images_direct() {
        let json = serde_json::json!({
            "$type": "app.bsky.embed.images",
            "images": [
                { "alt": "A test visual", "image": { "ref": { "$link": "bafkreicid12345" } } },
                { "alt": "Second visual", "image": { "cid": "bafkreicid67890" } }
            ]
        });
        let embed: Embed = serde_json::from_value(json).unwrap();
        let images = embed.extract_images();
        assert_eq!(images.len(), 2);
        assert_eq!(images[0].0, "bafkreicid12345");
        assert_eq!(images[1].0, "bafkreicid67890");
    }

    #[test]
    fn test_embed_extract_images_record_with_media() {
        let json = serde_json::json!({
            "$type": "app.bsky.embed.recordWithMedia",
            "record": {
                "record": { "uri": "at://did:plc:alice/app.bsky.feed.post/123", "cid": "bafyquoted" }
            },
            "media": {
                "$type": "app.bsky.embed.images",
                "images": [{ "alt": "Embedded image", "image": { "ref": { "$link": "bafkmediaimage1" } } }]
            }
        });
        let embed: Embed = serde_json::from_value(json).unwrap();
        let images = embed.extract_images();
        assert_eq!(images.len(), 1);
        assert_eq!(images[0].0, "bafkmediaimage1");
        assert!(embed.is_quote());
        assert_eq!(
            embed.quote_uri(),
            Some("at://did:plc:alice/app.bsky.feed.post/123")
        );
        assert_eq!(embed.quote_cid(), Some("bafyquoted"));
    }

    #[test]
    fn test_records_builders_gallery_labels_and_unix_secs_iso8601() {
        let root = StrongRef::new("at://did:plc:root/app.bsky.feed.post/1", "cid_root");
        let parent = StrongRef::new("at://did:plc:parent/app.bsky.feed.post/2", "cid_parent");
        let reply = ReplyRef::new(root.clone(), parent);
        assert_eq!(reply.root_did(), Some("did:plc:root"));
        assert_eq!(reply.parent_did(), Some("did:plc:parent"));

        let rec_embed = RecordEmbed::new(root);
        let rwm = RecordWithMediaEmbed::new(
            rec_embed.clone(),
            Some(serde_json::json!({
                "items": [
                    {"media": {"alt": "gallery alt", "image": {"ref": {"$link": "bafygallery1"}}}},
                    {"cid": "bafygallery2"}
                ]
            })),
        );
        let embed_rec = Embed::Record(rec_embed);
        assert!(embed_rec.is_quote());
        assert_eq!(embed_rec.quote_cid(), Some("cid_root"));
        assert!(embed_rec.extract_images().is_empty());

        let embed_rwm = Embed::RecordWithMedia(Box::new(rwm));
        let rwm_imgs = embed_rwm.extract_images();
        assert_eq!(rwm_imgs.len(), 2);
        assert_eq!(
            rwm_imgs[0],
            ("bafygallery1".to_string(), "gallery alt".to_string())
        );

        let embed_gallery = Embed::Gallery(serde_json::json!({
            "items": [{"alt": "g1", "image": {"cid": "bafyg1"}}]
        }));
        assert!(!embed_gallery.is_quote());
        assert_eq!(embed_gallery.quote_uri(), None);
        assert_eq!(embed_gallery.quote_cid(), None);
        assert_eq!(embed_gallery.extract_images().len(), 1);
        assert!(Embed::extract_gallery_items(&serde_json::json!({})).is_empty());

        let rwm_no_media = Embed::RecordWithMedia(Box::new(RecordWithMediaEmbed::new(
            RecordEmbed::new(StrongRef::new("at://did:plc:x/col/1", "c")),
            None,
        )));
        assert!(rwm_no_media.extract_images().is_empty());

        // SelfLabel / SelfLabels / has_nsfw_self_label
        let sl = SelfLabel::new("Porn");
        let sls = SelfLabels {
            record_type: None,
            values: vec![sl],
        };
        assert!(sls.has_nsfw());
        assert!(sls.contains("porn"));
        assert!(!sls.contains("safe"));
        assert!(has_nsfw_self_label(&serde_json::json!({
            "labels": {"values": [{"val": "nudity"}]}
        })));
        assert!(has_nsfw_self_label(&serde_json::json!({
            "labels": {"values": ["suggestive"]}
        })));
        assert!(!has_nsfw_self_label(&serde_json::json!({
            "labels": {"values": [{"val": "clean"}]}
        })));
        assert!(!has_nsfw_self_label(&serde_json::json!({})));

        // PostRecord, FollowRecord, ModListRecord::new, ListBlockRecord, format_unix_secs_iso8601
        let facet = crate::lexicon::Facet::new(
            crate::lexicon::ByteSlice::new(0, 6),
            vec![crate::lexicon::FacetFeature::Mention {
                did: "did:plc:mentioned".to_string(),
            }],
        );
        let post = PostRecord::new("hi @alice", "2026-11-03T00:00:00Z")
            .with_reply(reply)
            .with_facets(vec![facet])
            .with_embed(embed_rec);
        assert_eq!(
            post.mentioned_dids().collect::<Vec<_>>(),
            vec!["did:plc:mentioned"]
        );
        assert_eq!(
            post.quote_uri(),
            Some("at://did:plc:root/app.bsky.feed.post/1")
        );

        let follow = FollowRecord::new("did:plc:target", "2026-11-03T00:00:00Z");
        assert_eq!(follow.subject, "did:plc:target");

        let curatelist = ModListRecord::new(
            "app.bsky.graph.defs#curatelist",
            "Curate",
            None,
            "2026-11-03T00:00:00Z",
        );
        assert!(!curatelist.is_modlist());

        let lb = ListBlockRecord::new(
            "at://did:plc:alice/app.bsky.graph.list/1",
            "2026-11-03T00:00:00Z",
        );
        assert_eq!(lb.subject, "at://did:plc:alice/app.bsky.graph.list/1");

        assert_eq!(format_unix_secs_iso8601(0), "1970-01-01T00:00:00Z");
        assert_eq!(
            format_unix_secs_iso8601(1_790_906_400),
            "2026-10-02T02:00:00Z"
        );
    }
}