toku-core 0.2.1

Domain models, traits, and state machine for Toku book manager
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// A book in the user's library. Each row represents an edition (Book = Edition).
/// Set `work_id` to link this edition to a `Work` for grouping.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Book {
    pub id: Uuid,
    pub title: String,
    pub subtitle: Option<String>,
    pub description: Option<String>,
    pub page_count: Option<i32>,
    pub pub_date: Option<String>,
    pub language: Option<String>,
    pub format: BookFormat,
    /// Duration in minutes — only meaningful for audiobooks.
    pub duration_minutes: Option<i32>,
    pub cover_hash: Option<String>,
    /// Links this edition to a Work (for grouping editions).
    pub work_id: Option<Uuid>,
    pub status: ReadingStatus,
    pub rating: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl Book {
    pub fn new(title: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::now_v7(),
            title: title.into(),
            subtitle: None,
            description: None,
            page_count: None,
            pub_date: None,
            language: None,
            format: BookFormat::Physical,
            duration_minutes: None,
            cover_hash: None,
            work_id: None,
            status: ReadingStatus::WantToRead,
            rating: None,
            created_at: now,
            updated_at: now,
        }
    }
}

/// Physical book, ebook, or audiobook.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BookFormat {
    Physical,
    Ebook,
    Audiobook,
}

impl BookFormat {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Physical => "physical",
            Self::Ebook => "ebook",
            Self::Audiobook => "audiobook",
        }
    }
}

impl std::fmt::Display for BookFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for BookFormat {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "physical" => Ok(Self::Physical),
            "ebook" => Ok(Self::Ebook),
            "audiobook" => Ok(Self::Audiobook),
            _ => Err(crate::TokuError::InvalidFormat(s.to_string())),
        }
    }
}

/// A reading session tracks a single reading attempt of a book.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadingSession {
    pub id: Uuid,
    pub book_id: Uuid,
    pub started_at: DateTime<Utc>,
    pub finished_at: Option<DateTime<Utc>>,
    pub start_page: Option<i32>,
    pub end_page: Option<i32>,
    pub rating: Option<i32>,
    pub notes: Option<String>,
    pub created_at: DateTime<Utc>,
}

impl ReadingSession {
    pub fn new(book_id: Uuid) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::now_v7(),
            book_id,
            started_at: now,
            finished_at: None,
            start_page: None,
            end_page: None,
            rating: None,
            notes: None,
            created_at: now,
        }
    }
}

/// Type of reading progress entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProgressType {
    Page,
    Percent,
    Chapter,
    /// Duration in minutes (for audiobooks).
    Duration,
}

impl ProgressType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Page => "page",
            Self::Percent => "percent",
            Self::Chapter => "chapter",
            Self::Duration => "duration",
        }
    }
}

impl std::fmt::Display for ProgressType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ProgressType {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "page" => Ok(Self::Page),
            "percent" => Ok(Self::Percent),
            "chapter" => Ok(Self::Chapter),
            "duration" => Ok(Self::Duration),
            _ => Err(crate::TokuError::InvalidProgressType(s.to_string())),
        }
    }
}

/// A timestamped reading progress entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadingProgress {
    pub id: Uuid,
    pub book_id: Uuid,
    pub session_id: Option<Uuid>,
    pub progress_type: ProgressType,
    pub value: i32,
    pub note: Option<String>,
    pub logged_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
}

impl ReadingProgress {
    pub fn new(book_id: Uuid, progress_type: ProgressType, value: i32) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::now_v7(),
            book_id,
            session_id: None,
            progress_type,
            value,
            note: None,
            logged_at: now,
            created_at: now,
        }
    }
}

/// Parse a human-friendly duration string into total minutes.
///
/// Accepted formats: `5h30m`, `330m`, `5.5h`, `5h`, `90`.
pub fn parse_duration_to_minutes(s: &str) -> Result<i32, crate::TokuError> {
    let s = s.trim();

    // Try `Xh Ym` or `XhYm`
    if let Some(h_pos) = s.find('h') {
        let hours_str = &s[..h_pos];
        let rest = s[h_pos + 1..].trim();

        if rest.is_empty() {
            // Could be fractional hours like "5.5h"
            let hours: f64 = hours_str
                .parse()
                .map_err(|_| crate::TokuError::InvalidDuration(s.to_string()))?;
            return Ok((hours * 60.0).round() as i32);
        }

        let mins_str = rest.trim_end_matches('m');
        let hours: f64 = hours_str
            .parse()
            .map_err(|_| crate::TokuError::InvalidDuration(s.to_string()))?;
        let mins: f64 = mins_str
            .parse()
            .map_err(|_| crate::TokuError::InvalidDuration(s.to_string()))?;
        return Ok((hours * 60.0 + mins).round() as i32);
    }

    // Try `Xm`
    if let Some(m_str) = s.strip_suffix('m') {
        let mins: f64 = m_str
            .parse()
            .map_err(|_| crate::TokuError::InvalidDuration(s.to_string()))?;
        return Ok(mins.round() as i32);
    }

    // Plain number = minutes
    let mins: f64 = s
        .parse()
        .map_err(|_| crate::TokuError::InvalidDuration(s.to_string()))?;
    Ok(mins.round() as i32)
}

/// Reading lifecycle states.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReadingStatus {
    WantToRead,
    Reading,
    Read,
    Abandoned,
    OnHold,
}

impl ReadingStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::WantToRead => "want-to-read",
            Self::Reading => "reading",
            Self::Read => "read",
            Self::Abandoned => "abandoned",
            Self::OnHold => "on-hold",
        }
    }

    /// Returns whether a transition from this status to `target` is valid.
    pub fn can_transition_to(&self, target: &ReadingStatus) -> bool {
        matches!(
            (self, target),
            (ReadingStatus::WantToRead, ReadingStatus::Reading)
                | (ReadingStatus::Reading, ReadingStatus::Read)
                | (ReadingStatus::Reading, ReadingStatus::Abandoned)
                | (ReadingStatus::Reading, ReadingStatus::OnHold)
                | (ReadingStatus::OnHold, ReadingStatus::Reading)
                | (ReadingStatus::Abandoned, ReadingStatus::Reading)
                | (ReadingStatus::Read, ReadingStatus::Reading) // re-read
        )
    }
}

impl std::fmt::Display for ReadingStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ReadingStatus {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "want-to-read" | "to-read" => Ok(Self::WantToRead),
            "reading" | "currently-reading" => Ok(Self::Reading),
            "read" => Ok(Self::Read),
            "abandoned" | "dnf" => Ok(Self::Abandoned),
            "on-hold" | "paused" => Ok(Self::OnHold),
            _ => Err(crate::TokuError::InvalidStatus(s.to_string())),
        }
    }
}

/// Contributor role for a book.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContributorRole {
    Author,
    Editor,
    Translator,
    Illustrator,
    Narrator,
}

impl ContributorRole {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Author => "author",
            Self::Editor => "editor",
            Self::Translator => "translator",
            Self::Illustrator => "illustrator",
            Self::Narrator => "narrator",
        }
    }
}

impl std::fmt::Display for ContributorRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ContributorRole {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "author" => Ok(Self::Author),
            "editor" => Ok(Self::Editor),
            "translator" => Ok(Self::Translator),
            "illustrator" => Ok(Self::Illustrator),
            "narrator" => Ok(Self::Narrator),
            _ => Err(crate::TokuError::InvalidRole(s.to_string())),
        }
    }
}

/// An author or other contributor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Author {
    pub id: Uuid,
    pub name: String,
    pub sort_name: Option<String>,
}

impl Author {
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        let sort_name = guess_sort_name(&name);
        Self {
            id: Uuid::now_v7(),
            name,
            sort_name: Some(sort_name),
        }
    }
}

/// Guess a sort name from a display name: "Ursula K. Le Guin" → "Le Guin, Ursula K."
fn guess_sort_name(name: &str) -> String {
    let parts: Vec<&str> = name.split_whitespace().collect();
    if parts.len() <= 1 {
        return name.to_string();
    }
    let last = parts.last().unwrap();
    let rest: Vec<&str> = parts[..parts.len() - 1].to_vec();
    format!("{}, {}", last, rest.join(" "))
}

/// A user-defined shelf for organizing books (e.g. "Favorites", "To Re-read").
/// Smart shelves have `is_smart = true` and a `smart_filter` that dynamically matches books.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Shelf {
    pub id: Uuid,
    pub name: String,
    pub is_smart: bool,
    pub smart_filter: Option<String>,
    pub created_at: DateTime<Utc>,
}

impl Shelf {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            id: Uuid::now_v7(),
            name: name.into(),
            is_smart: false,
            smart_filter: None,
            created_at: Utc::now(),
        }
    }

    pub fn new_smart(name: impl Into<String>, filter_json: String) -> Self {
        Self {
            id: Uuid::now_v7(),
            name: name.into(),
            is_smart: true,
            smart_filter: Some(filter_json),
            created_at: Utc::now(),
        }
    }
}

/// Type of tag: general, mood, pace, or content warning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TagType {
    General,
    Mood,
    Pace,
    ContentWarning,
}

impl TagType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::General => "general",
            Self::Mood => "mood",
            Self::Pace => "pace",
            Self::ContentWarning => "content_warning",
        }
    }
}

impl std::fmt::Display for TagType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for TagType {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "general" => Ok(Self::General),
            "mood" => Ok(Self::Mood),
            "pace" => Ok(Self::Pace),
            "content_warning" | "content-warning" | "cw" => Ok(Self::ContentWarning),
            _ => Err(crate::TokuError::InvalidTagType(s.to_string())),
        }
    }
}

/// Pace rating for a book: fast, medium, or slow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PaceRating {
    Fast,
    Medium,
    Slow,
}

impl PaceRating {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Fast => "fast",
            Self::Medium => "medium",
            Self::Slow => "slow",
        }
    }
}

impl std::fmt::Display for PaceRating {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for PaceRating {
    type Err = crate::TokuError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "fast" => Ok(Self::Fast),
            "medium" | "med" => Ok(Self::Medium),
            "slow" => Ok(Self::Slow),
            _ => Err(crate::TokuError::InvalidPaceRating(s.to_string())),
        }
    }
}

/// A user-defined tag for categorizing books (e.g. "sci-fi", "Hugo winner").
/// Tag names are case-insensitive. Tags are unique by `(name, tag_type)`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
    pub id: Uuid,
    pub name: String,
    pub tag_type: TagType,
    pub created_at: DateTime<Utc>,
}

impl Tag {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            id: Uuid::now_v7(),
            name: name.into(),
            tag_type: TagType::General,
            created_at: Utc::now(),
        }
    }

    pub fn with_type(name: impl Into<String>, tag_type: TagType) -> Self {
        Self {
            id: Uuid::now_v7(),
            name: name.into(),
            tag_type,
            created_at: Utc::now(),
        }
    }
}

/// A book-to-author relationship with role and ordering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BookAuthor {
    pub book_id: Uuid,
    pub author_id: Uuid,
    pub role: ContributorRole,
    pub position: i32,
}

/// A named series of books.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Series {
    pub id: Uuid,
    pub name: String,
    pub total_books: Option<i32>,
}

/// A book's position within a series. Position is TEXT to handle "1.5", "2a", etc.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BookSeries {
    pub book_id: Uuid,
    pub series_id: Uuid,
    pub position: Option<String>,
}

/// A Work groups multiple editions (Books) of the same creative work.
/// E.g. "Dune" hardcover, paperback, and Kindle editions share one Work.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Work {
    pub id: Uuid,
    pub title: String,
    pub original_language: Option<String>,
    pub first_published: Option<String>,
    pub created_at: DateTime<Utc>,
}

impl Work {
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            id: Uuid::now_v7(),
            title: title.into(),
            original_language: None,
            first_published: None,
            created_at: Utc::now(),
        }
    }
}

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

    #[test]
    fn book_new_has_defaults() {
        let book = Book::new("Dune");
        assert_eq!(book.title, "Dune");
        assert_eq!(book.status, ReadingStatus::WantToRead);
        assert_eq!(book.format, BookFormat::Physical);
        assert!(book.subtitle.is_none());
        assert!(book.rating.is_none());
    }

    #[test]
    fn work_new_has_defaults() {
        let work = Work::new("Dune");
        assert_eq!(work.title, "Dune");
        assert!(work.original_language.is_none());
        assert!(work.first_published.is_none());
    }

    #[test]
    fn author_sort_name() {
        // Naive heuristic: last word becomes sort key.
        // "Le Guin" is a known limitation — users can manually set sort_name.
        let author = Author::new("Frank Herbert");
        assert_eq!(author.sort_name.as_deref(), Some("Herbert, Frank"));
    }

    #[test]
    fn author_single_name() {
        let author = Author::new("Voltaire");
        assert_eq!(author.sort_name.as_deref(), Some("Voltaire"));
    }

    #[test]
    fn reading_status_roundtrip() {
        for status in [
            ReadingStatus::WantToRead,
            ReadingStatus::Reading,
            ReadingStatus::Read,
            ReadingStatus::Abandoned,
            ReadingStatus::OnHold,
        ] {
            let parsed: ReadingStatus = status.as_str().parse().unwrap();
            assert_eq!(parsed, status);
        }
    }

    #[test]
    fn book_format_roundtrip() {
        for fmt in [
            BookFormat::Physical,
            BookFormat::Ebook,
            BookFormat::Audiobook,
        ] {
            let parsed: BookFormat = fmt.as_str().parse().unwrap();
            assert_eq!(parsed, fmt);
        }
    }

    #[test]
    fn reading_status_goodreads_aliases() {
        assert_eq!(
            "currently-reading".parse::<ReadingStatus>().unwrap(),
            ReadingStatus::Reading
        );
        assert_eq!(
            "to-read".parse::<ReadingStatus>().unwrap(),
            ReadingStatus::WantToRead
        );
        assert_eq!(
            "dnf".parse::<ReadingStatus>().unwrap(),
            ReadingStatus::Abandoned
        );
    }

    // --- State machine tests ---

    #[test]
    fn valid_transitions() {
        let valid = [
            (ReadingStatus::WantToRead, ReadingStatus::Reading),
            (ReadingStatus::Reading, ReadingStatus::Read),
            (ReadingStatus::Reading, ReadingStatus::Abandoned),
            (ReadingStatus::Reading, ReadingStatus::OnHold),
            (ReadingStatus::OnHold, ReadingStatus::Reading),
            (ReadingStatus::Abandoned, ReadingStatus::Reading),
            (ReadingStatus::Read, ReadingStatus::Reading), // re-read
        ];

        for (from, to) in &valid {
            assert!(from.can_transition_to(to), "{from} → {to} should be valid");
        }
    }

    #[test]
    fn invalid_transitions() {
        let invalid = [
            (ReadingStatus::WantToRead, ReadingStatus::Read),
            (ReadingStatus::WantToRead, ReadingStatus::Abandoned),
            (ReadingStatus::WantToRead, ReadingStatus::OnHold),
            (ReadingStatus::Read, ReadingStatus::Abandoned),
            (ReadingStatus::Read, ReadingStatus::OnHold),
            (ReadingStatus::Read, ReadingStatus::WantToRead),
            (ReadingStatus::Abandoned, ReadingStatus::Read),
            (ReadingStatus::Abandoned, ReadingStatus::OnHold),
            (ReadingStatus::OnHold, ReadingStatus::Read),
            (ReadingStatus::OnHold, ReadingStatus::Abandoned),
            // Self-transitions
            (ReadingStatus::Reading, ReadingStatus::Reading),
            (ReadingStatus::WantToRead, ReadingStatus::WantToRead),
        ];

        for (from, to) in &invalid {
            assert!(
                !from.can_transition_to(to),
                "{from} → {to} should be invalid"
            );
        }
    }

    #[test]
    fn reading_session_new_defaults() {
        let book_id = Uuid::now_v7();
        let session = ReadingSession::new(book_id);
        assert_eq!(session.book_id, book_id);
        assert!(session.finished_at.is_none());
        assert!(session.rating.is_none());
        assert!(session.notes.is_none());
    }

    #[test]
    fn progress_type_roundtrip() {
        for pt in [
            ProgressType::Page,
            ProgressType::Percent,
            ProgressType::Chapter,
            ProgressType::Duration,
        ] {
            let parsed: ProgressType = pt.as_str().parse().unwrap();
            assert_eq!(parsed, pt);
        }
    }

    #[test]
    fn progress_type_display() {
        assert_eq!(ProgressType::Page.to_string(), "page");
        assert_eq!(ProgressType::Duration.to_string(), "duration");
    }

    #[test]
    fn progress_type_invalid() {
        assert!("invalid".parse::<ProgressType>().is_err());
    }

    #[test]
    fn reading_progress_new_defaults() {
        let book_id = Uuid::now_v7();
        let progress = ReadingProgress::new(book_id, ProgressType::Page, 42);
        assert_eq!(progress.book_id, book_id);
        assert_eq!(progress.progress_type, ProgressType::Page);
        assert_eq!(progress.value, 42);
        assert!(progress.session_id.is_none());
        assert!(progress.note.is_none());
    }

    #[test]
    fn parse_duration_hours_minutes() {
        assert_eq!(parse_duration_to_minutes("5h30m").unwrap(), 330);
        assert_eq!(parse_duration_to_minutes("1h0m").unwrap(), 60);
        assert_eq!(parse_duration_to_minutes("0h45m").unwrap(), 45);
    }

    #[test]
    fn parse_duration_minutes_only() {
        assert_eq!(parse_duration_to_minutes("330m").unwrap(), 330);
        assert_eq!(parse_duration_to_minutes("90m").unwrap(), 90);
    }

    #[test]
    fn parse_duration_hours_only() {
        assert_eq!(parse_duration_to_minutes("5h").unwrap(), 300);
        assert_eq!(parse_duration_to_minutes("5.5h").unwrap(), 330);
        assert_eq!(parse_duration_to_minutes("2.25h").unwrap(), 135);
    }

    #[test]
    fn parse_duration_plain_number() {
        assert_eq!(parse_duration_to_minutes("90").unwrap(), 90);
    }

    #[test]
    fn parse_duration_invalid() {
        assert!(parse_duration_to_minutes("abc").is_err());
        assert!(parse_duration_to_minutes("").is_err());
    }

    #[test]
    fn tag_type_roundtrip() {
        for tt in [
            TagType::General,
            TagType::Mood,
            TagType::Pace,
            TagType::ContentWarning,
        ] {
            let parsed: TagType = tt.as_str().parse().unwrap();
            assert_eq!(parsed, tt);
        }
    }

    #[test]
    fn tag_type_aliases() {
        assert_eq!(
            "content-warning".parse::<TagType>().unwrap(),
            TagType::ContentWarning
        );
        assert_eq!("cw".parse::<TagType>().unwrap(), TagType::ContentWarning);
    }

    #[test]
    fn tag_type_invalid() {
        assert!("unknown".parse::<TagType>().is_err());
    }

    #[test]
    fn pace_rating_roundtrip() {
        for pr in [PaceRating::Fast, PaceRating::Medium, PaceRating::Slow] {
            let parsed: PaceRating = pr.as_str().parse().unwrap();
            assert_eq!(parsed, pr);
        }
    }

    #[test]
    fn pace_rating_alias_med() {
        assert_eq!("med".parse::<PaceRating>().unwrap(), PaceRating::Medium);
    }

    #[test]
    fn pace_rating_invalid() {
        assert!("very-fast".parse::<PaceRating>().is_err());
    }

    #[test]
    fn tag_with_type() {
        let tag = Tag::with_type("adventurous", TagType::Mood);
        assert_eq!(tag.name, "adventurous");
        assert_eq!(tag.tag_type, TagType::Mood);
    }

    #[test]
    fn tag_new_defaults_to_general() {
        let tag = Tag::new("sci-fi");
        assert_eq!(tag.tag_type, TagType::General);
    }
}